@ohif/extension-measurement-tracking 0.0.1 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dist/ohif-extension-measurement-tracking.umd.js","mappings":";CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,EAAQG,QAAQ,YAAaA,QAAQ,cAAeA,QAAQ,wCAAyCA,QAAQ,wBAAyBA,QAAQ,wBACtI,mBAAXC,QAAyBA,OAAOC,IAC9CD,OAAO,CAAC,WAAY,aAAc,uCAAwC,uBAAwB,uBAAwBJ,GAChG,iBAAZC,QACdA,QAAQ,uCAAyCD,EAAQG,QAAQ,YAAaA,QAAQ,cAAeA,QAAQ,wCAAyCA,QAAQ,wBAAyBA,QAAQ,wBAE/LJ,EAAK,uCAAyCC,EAAQD,EAAK,YAAaA,EAAK,cAAeA,EAAK,wCAAyCA,EAAK,wBAAyBA,EAAK,uBAC9K,CATD,CASGO,YAAY,CAACC,EAAkCC,EAAkCC,EAAkCC,EAAkCC,cCTpJC,ECCAC,EADAC,ECKAC,sCCJJ,IAAIC,EAAYC,MAAQA,KAAKD,UAAa,WAStC,OARAA,EAAWE,OAAOC,QAAU,SAASC,GACjC,IAAK,IAAIC,EAAGC,EAAI,EAAGC,EAAIC,UAAUC,OAAQH,EAAIC,EAAGD,IAE5C,IAAK,IAAII,KADTL,EAAIG,UAAUF,GACOJ,OAAOS,UAAUC,eAAeC,KAAKR,EAAGK,KACzDN,EAAEM,GAAKL,EAAEK,IAEjB,OAAON,CACX,EACOJ,EAASc,MAAMb,KAAMO,UAChC,EACIO,EAAUd,MAAQA,KAAKc,QAAW,SAAUV,EAAGW,GAC/C,IAAIZ,EAAI,CAAC,EACT,IAAK,IAAIM,KAAKL,EAAOH,OAAOS,UAAUC,eAAeC,KAAKR,EAAGK,IAAMM,EAAEC,QAAQ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gBAAiByI,IAAAA,MAAgB,CAC/BvQ,SAAUuQ,IAAAA,MAAgB,CACxB5F,mBAAoB4F,IAAAA,MAAgB,CAClCnE,gBAAiBmE,IAAAA,KAAAA,WACjBgxC,YAAahxC,IAAAA,OAAAA,aACZ6F,aACFA,aACFA,YA+DL,UEtUA,QAhCA,SAAuBvO,GAIL,IAJM,gBACtByB,EAAe,iBACfvB,EAAgB,gBAChBD,GACDD,EACC,MAAO,CACL,CACE6I,KAAM,aACNyyC,SAAU,eACVC,UAAW,UACXn4C,MAAO,UACP+K,UAAWu9B,EAAAA,KAA+B,KAAM,CAC9CjqC,kBACAvB,mBACAD,qBAIJ,CACE4I,KAAM,sBACNyyC,SAAU,aACVC,UAAW,UACXn4C,MAAO,eACP+K,UAAW0pC,EAAAA,KAAmC,KAAM,CAClDp2C,kBACAvB,mBACAD,qBAIR,sOCtCA,MAAMmO,EAAY7M,EAAAA,MAAW,IACpB,wCAKHi6C,EAA0BtyC,GAE5B3H,EAAAA,cAACA,EAAAA,SAAc,CAACk6C,SAAUl6C,EAAAA,cAAA,WAAK,eAC7BA,EAAAA,cAAC6M,EAAclF,IA6BrB,QAxBA,SAA0BlJ,GAIvB,IAJwB,gBACzBC,EAAe,gBACfwB,EAAe,iBACfvB,GACDF,EAYC,MAAO,CACL,CACE6I,KAAM,sBACNsF,UAd4CjF,GAE5C3H,EAAAA,cAACi6C,EAAuBltC,EAAA,CACtBrO,gBAAiBA,EACjBwB,gBAAiBA,EACjBvB,iBAAkBA,GACdgJ,KAWZ,ECtBA,EAXqC,CAInC1O,+DCPSkhD,GDSTC,iBAAgB,IAChBC,eAAc,EACdC,kBAAiBA","sources":["webpack://ohif-extension-measurement-tracking/webpack/universalModuleDefinition","webpack://ohif-extension-measurement-tracking/webpack/runtime/chunk loaded","webpack://ohif-extension-measurement-tracking/webpack/runtime/create fake namespace object","webpack://ohif-extension-measurement-tracking/webpack/runtime/jsonp chunk loading","webpack://ohif-extension-measurement-tracking/../../../node_modules/@xstate/react/lib/index.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/@xstate/react/lib/useActor.js","webpack://ohif-extension-measurement-tracking/./contexts/TrackedMeasurementsContext/measurementTrackingMachine.js","webpack://ohif-extension-measurement-tracking/./contexts/TrackedMeasurementsContext/promptBeginTracking.js","webpack://ohif-extension-measurement-tracking/./contexts/TrackedMeasurementsContext/promptTrackNewSeries.js","webpack://ohif-extension-measurement-tracking/./contexts/TrackedMeasurementsContext/promptTrackNewStudy.js","webpack://ohif-extension-measurement-tracking/./_shared/createReportAsync.tsx","webpack://ohif-extension-measurement-tracking/./_shared/PROMPT_RESPONSES.js","webpack://ohif-extension-measurement-tracking/./_shared/getNextSRSeriesNumber.js","webpack://ohif-extension-measurement-tracking/./contexts/TrackedMeasurementsContext/promptSaveReport.js","webpack://ohif-extension-measurement-tracking/./_shared/createReportDialogPrompt.tsx","webpack://ohif-extension-measurement-tracking/./contexts/TrackedMeasurementsContext/promptHydrateStructuredReport.js","webpack://ohif-extension-measurement-tracking/./contexts/TrackedMeasurementsContext/hydrateStructuredReport.tsx","webpack://ohif-extension-measurement-tracking/./contexts/TrackedMeasurementsContext/TrackedMeasurementsContext.tsx","webpack://ohif-extension-measurement-tracking/./getContextModule.tsx","webpack://ohif-extension-measurement-tracking/./viewports/TrackedCornerstoneViewport.tsx","webpack://ohif-extension-measurement-tracking/../../../node_modules/lodash.debounce/index.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/object-assign/index.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/prop-types/factoryWithThrowingShims.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/prop-types/index.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/prop-types/lib/ReactPropTypesSecret.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/react/cjs/react.production.min.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/react/index.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/void-elements/index.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/_virtual/_tslib.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/types.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/actionTypes.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/utils.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/constants.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/environment.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/actions.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/serviceScope.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/Actor.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/stateUtils.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/State.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/scheduler.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/registry.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/devTools.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/behaviors.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/interpreter.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/invokeUtils.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/StateNode.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/Machine.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/mapState.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/match.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/schema.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/xstate/es/index.js","webpack://ohif-extension-measurement-tracking/external umd \"@cornerstonejs/core\"","webpack://ohif-extension-measurement-tracking/external umd \"@cornerstonejs/tools\"","webpack://ohif-extension-measurement-tracking/external umd \"@ohif/core\"","webpack://ohif-extension-measurement-tracking/external umd \"@ohif/extension-cornerstone-dicom-sr\"","webpack://ohif-extension-measurement-tracking/external umd \"@ohif/ui\"","webpack://ohif-extension-measurement-tracking/../../../node_modules/@babel/runtime/helpers/esm/typeof.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/@babel/runtime/helpers/esm/toPrimitive.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/@babel/runtime/helpers/esm/defineProperty.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/html-parse-stringify/dist/html-parse-stringify.module.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/react-i18next/dist/es/utils.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/react-i18next/dist/es/unescape.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/react-i18next/dist/es/defaults.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/react-i18next/dist/es/i18nInstance.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/@babel/runtime/helpers/esm/createClass.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/react-i18next/dist/es/context.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/@babel/runtime/helpers/esm/classCallCheck.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/@babel/runtime/helpers/esm/slicedToArray.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/@babel/runtime/helpers/esm/nonIterableRest.js","webpack://ohif-extension-measurement-tracking/../../../node_modules/react-i18next/dist/es/useTranslation.js","webpack://ohif-extension-measurement-tracking/webpack/bootstrap","webpack://ohif-extension-measurement-tracking/webpack/runtime/chunk prefetch function","webpack://ohif-extension-measurement-tracking/webpack/runtime/compat get default export","webpack://ohif-extension-measurement-tracking/webpack/runtime/define property getters","webpack://ohif-extension-measurement-tracking/webpack/runtime/global","webpack://ohif-extension-measurement-tracking/webpack/runtime/hasOwnProperty shorthand","webpack://ohif-extension-measurement-tracking/webpack/runtime/make namespace object","webpack://ohif-extension-measurement-tracking/webpack/runtime/startup prefetch","webpack://ohif-extension-measurement-tracking/./panels/PanelStudyBrowserTracking/PanelStudyBrowserTracking.tsx","webpack://ohif-extension-measurement-tracking/./panels/PanelStudyBrowserTracking/getImageSrcFromImageId.js","webpack://ohif-extension-measurement-tracking/./panels/PanelStudyBrowserTracking/requestDisplaySetCreationForStudy.js","webpack://ohif-extension-measurement-tracking/./panels/PanelStudyBrowserTracking/index.tsx","webpack://ohif-extension-measurement-tracking/../../../node_modules/@remix-run/router/dist/router.js","webpack://ohif-extension-measurement-tracking/../../../platform/app/node_modules/react-router/dist/index.js","webpack://ohif-extension-measurement-tracking/../../../platform/app/node_modules/react-router-dom/dist/index.js","webpack://ohif-extension-measurement-tracking/./panels/PanelMeasurementTableTracking/ActionButtons.tsx","webpack://ohif-extension-measurement-tracking/./panels/PanelMeasurementTableTracking/index.tsx","webpack://ohif-extension-measurement-tracking/../../../platform/app/src/hooks/useDebounce.js","webpack://ohif-extension-measurement-tracking/./getPanelModule.tsx","webpack://ohif-extension-measurement-tracking/./getViewportModule.tsx","webpack://ohif-extension-measurement-tracking/./index.tsx","webpack://ohif-extension-measurement-tracking/./id.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"@ohif/ui\"), require(\"@ohif/core\"), require(\"@ohif/extension-cornerstone-dicom-sr\"), require(\"@cornerstonejs/tools\"), require(\"@cornerstonejs/core\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"@ohif/ui\", \"@ohif/core\", \"@ohif/extension-cornerstone-dicom-sr\", \"@cornerstonejs/tools\", \"@cornerstonejs/core\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"ohif-extension-measurement-tracking\"] = factory(require(\"@ohif/ui\"), require(\"@ohif/core\"), require(\"@ohif/extension-cornerstone-dicom-sr\"), require(\"@cornerstonejs/tools\"), require(\"@cornerstonejs/core\"));\n\telse\n\t\troot[\"ohif-extension-measurement-tracking\"] = factory(root[\"@ohif/ui\"], root[\"@ohif/core\"], root[\"@ohif/extension-cornerstone-dicom-sr\"], root[\"@cornerstonejs/tools\"], root[\"@cornerstonejs/core\"]);\n})(globalThis, (__WEBPACK_EXTERNAL_MODULE__369__, __WEBPACK_EXTERNAL_MODULE__762__, __WEBPACK_EXTERNAL_MODULE__148__, __WEBPACK_EXTERNAL_MODULE__867__, __WEBPACK_EXTERNAL_MODULE__464__) => {\nreturn ","var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t143: 0\n};\n\n// no chunk on demand loading\n\n__webpack_require__.F.j = (chunkId) => {\n\tif((!__webpack_require__.o(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && true) {\n\t\tinstalledChunks[chunkId] = null;\n\t\tvar link = document.createElement('link');\n\n\t\tif (__webpack_require__.nc) {\n\t\t\tlink.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tlink.rel = \"prefetch\";\n\t\tlink.as = \"script\";\n\t\tlink.href = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\tdocument.head.appendChild(link);\n\t}\n};\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// no jsonp function","\"use strict\";\nvar __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar react_1 = require(\"react\");\nvar xstate_1 = require(\"xstate\");\nvar defaultOptions = {\n immediate: false\n};\nfunction useMachine(machine, options) {\n if (options === void 0) { options = defaultOptions; }\n var context = options.context, guards = options.guards, actions = options.actions, activities = options.activities, services = options.services, delays = options.delays, immediate = options.immediate, rehydratedState = options.state, interpreterOptions = __rest(options, [\"context\", \"guards\", \"actions\", \"activities\", \"services\", \"delays\", \"immediate\", \"state\"]);\n var machineConfig = {\n context: context,\n guards: guards,\n actions: actions,\n activities: activities,\n services: services,\n delays: delays\n };\n // Reference the machine\n var machineRef = react_1.useRef(null);\n // Create the machine only once\n // See https://reactjs.org/docs/hooks-faq.html#how-to-create-expensive-objects-lazily\n if (machineRef.current === null) {\n machineRef.current = machine.withConfig(machineConfig, __assign(__assign({}, machine.context), context));\n }\n // Reference the service\n var serviceRef = react_1.useRef(null);\n // Create the service only once\n if (serviceRef.current === null) {\n serviceRef.current = xstate_1.interpret(machineRef.current, interpreterOptions).onTransition(function (state) {\n // Update the current machine state when a transition occurs\n if (state.changed) {\n setCurrent(state);\n }\n });\n }\n var service = serviceRef.current;\n // Make sure actions and services are kept updated when they change.\n // This mutation assignment is safe because the service instance is only used\n // in one place -- this hook's caller.\n react_1.useEffect(function () {\n Object.assign(service.machine.options.actions, actions);\n }, [actions]);\n react_1.useEffect(function () {\n Object.assign(service.machine.options.services, services);\n }, [services]);\n // Keep track of the current machine state\n var initialState = rehydratedState\n ? xstate_1.State.create(rehydratedState)\n : service.initialState;\n var _a = __read(react_1.useState(function () { return initialState; }), 2), current = _a[0], setCurrent = _a[1];\n // Start service immediately (before mount) if specified in options\n if (immediate) {\n service.start();\n }\n react_1.useEffect(function () {\n // Start the service when the component mounts.\n // Note: the service will start only if it hasn't started already.\n //\n // If a rehydrated state was provided, use the resolved `initialState`.\n service.start(rehydratedState ? initialState : undefined);\n return function () {\n // Stop the service when the component unmounts\n service.stop();\n };\n }, []);\n return [current, service.send, service];\n}\nexports.useMachine = useMachine;\nfunction useService(service) {\n var _a = __read(react_1.useState(service.state), 2), current = _a[0], setCurrent = _a[1];\n react_1.useEffect(function () {\n // Set to current service state as there is a possibility\n // of a transition occurring between the initial useState()\n // initialization and useEffect() commit.\n setCurrent(service.state);\n var listener = function (state) {\n if (state.changed) {\n setCurrent(state);\n }\n };\n var sub = service.subscribe(listener);\n return function () {\n sub.unsubscribe();\n };\n }, [service]);\n return [current, service.send, service];\n}\nexports.useService = useService;\nvar useActor_1 = require(\"./useActor\");\nexports.useActor = useActor_1.useActor;\n//# sourceMappingURL=index.js.map","\"use strict\";\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar react_1 = require(\"react\");\nfunction useActor(actor) {\n var _a = __read(react_1.useState(undefined), 2), current = _a[0], setCurrent = _a[1];\n var actorRef = react_1.useRef(actor);\n react_1.useEffect(function () {\n if (actor) {\n actorRef.current = actor;\n var sub_1 = actor.subscribe(setCurrent);\n return function () {\n sub_1.unsubscribe();\n };\n }\n }, [actor]);\n return [current, actorRef.current ? actorRef.current.send : function () { return void 0; }];\n}\nexports.useActor = useActor;\n//# sourceMappingURL=useActor.js.map","import { hydrateStructuredReport } from '@ohif/extension-cornerstone-dicom-sr';\nimport { assign } from 'xstate';\n\nconst RESPONSE = {\n NO_NEVER: -1,\n CANCEL: 0,\n CREATE_REPORT: 1,\n ADD_SERIES: 2,\n SET_STUDY_AND_SERIES: 3,\n NO_NOT_FOR_SERIES: 4,\n HYDRATE_REPORT: 5,\n};\n\nconst machineConfiguration = {\n id: 'measurementTracking',\n initial: 'idle',\n context: {\n trackedStudy: '',\n trackedSeries: [],\n ignoredSeries: [],\n //\n prevTrackedStudy: '',\n prevTrackedSeries: [],\n prevIgnoredSeries: [],\n //\n ignoredSRSeriesForHydration: [],\n isDirty: false,\n },\n states: {\n off: {\n type: 'final',\n },\n idle: {\n entry: 'clearContext',\n on: {\n TRACK_SERIES: 'promptBeginTracking',\n // Unused? We may only do PROMPT_HYDRATE_SR now?\n SET_TRACKED_SERIES: [\n {\n target: 'tracking',\n actions: ['setTrackedStudyAndMultipleSeries', 'setIsDirtyToClean'],\n },\n ],\n PROMPT_HYDRATE_SR: {\n target: 'promptHydrateStructuredReport',\n cond: 'hasNotIgnoredSRSeriesForHydration',\n },\n RESTORE_PROMPT_HYDRATE_SR: 'promptHydrateStructuredReport',\n HYDRATE_SR: 'hydrateStructuredReport',\n },\n },\n promptBeginTracking: {\n invoke: {\n src: 'promptBeginTracking',\n onDone: [\n {\n target: 'tracking',\n actions: ['setTrackedStudyAndSeries', 'setIsDirty'],\n cond: 'shouldSetStudyAndSeries',\n },\n {\n target: 'off',\n cond: 'shouldKillMachine',\n },\n {\n target: 'idle',\n },\n ],\n onError: {\n target: 'idle',\n },\n },\n },\n tracking: {\n on: {\n TRACK_SERIES: [\n {\n target: 'promptTrackNewStudy',\n cond: 'isNewStudy',\n },\n {\n target: 'promptTrackNewSeries',\n cond: 'isNewSeries',\n },\n ],\n UNTRACK_SERIES: [\n {\n target: 'tracking',\n actions: ['removeTrackedSeries', 'setIsDirty'],\n cond: 'hasRemainingTrackedSeries',\n },\n {\n target: 'idle',\n },\n ],\n SET_TRACKED_SERIES: [\n {\n target: 'tracking',\n actions: ['setTrackedStudyAndMultipleSeries'],\n },\n ],\n SAVE_REPORT: 'promptSaveReport',\n SET_DIRTY: [\n {\n target: 'tracking',\n actions: ['setIsDirty'],\n cond: 'shouldSetDirty',\n },\n {\n target: 'tracking',\n },\n ],\n },\n },\n promptTrackNewSeries: {\n invoke: {\n src: 'promptTrackNewSeries',\n onDone: [\n {\n target: 'tracking',\n actions: ['addTrackedSeries', 'setIsDirty'],\n cond: 'shouldAddSeries',\n },\n {\n target: 'tracking',\n actions: [\n 'discardPreviouslyTrackedMeasurements',\n 'setTrackedStudyAndSeries',\n 'setIsDirty',\n ],\n cond: 'shouldSetStudyAndSeries',\n },\n {\n target: 'promptSaveReport',\n cond: 'shouldPromptSaveReport',\n },\n {\n target: 'tracking',\n },\n ],\n onError: {\n target: 'idle',\n },\n },\n },\n promptTrackNewStudy: {\n invoke: {\n src: 'promptTrackNewStudy',\n onDone: [\n {\n target: 'tracking',\n actions: [\n 'discardPreviouslyTrackedMeasurements',\n 'setTrackedStudyAndSeries',\n 'setIsDirty',\n ],\n cond: 'shouldSetStudyAndSeries',\n },\n {\n target: 'tracking',\n actions: ['ignoreSeries'],\n cond: 'shouldAddIgnoredSeries',\n },\n {\n target: 'promptSaveReport',\n cond: 'shouldPromptSaveReport',\n },\n {\n target: 'tracking',\n },\n ],\n onError: {\n target: 'idle',\n },\n },\n },\n promptSaveReport: {\n invoke: {\n src: 'promptSaveReport',\n onDone: [\n // \"clicked the save button\"\n // - should clear all measurements\n // - show DICOM SR\n {\n target: 'idle',\n actions: [\n 'clearAllMeasurements',\n 'showStructuredReportDisplaySetInActiveViewport',\n ],\n cond: 'shouldSaveAndContinueWithSameReport',\n },\n // \"starting a new report\"\n // - remove \"just saved\" measurements\n // - start tracking a new study + report\n {\n target: 'tracking',\n actions: [\n 'discardPreviouslyTrackedMeasurements',\n 'setTrackedStudyAndSeries',\n ],\n cond: 'shouldSaveAndStartNewReport',\n },\n // Cancel, back to tracking\n {\n target: 'tracking',\n },\n ],\n onError: {\n target: 'idle',\n },\n },\n },\n promptHydrateStructuredReport: {\n invoke: {\n src: 'promptHydrateStructuredReport',\n onDone: [\n {\n target: 'tracking',\n actions: [\n 'setTrackedStudyAndMultipleSeries',\n 'jumpToFirstMeasurementInActiveViewport',\n 'setIsDirtyToClean',\n ],\n cond: 'shouldHydrateStructuredReport',\n },\n {\n target: 'idle',\n actions: ['ignoreHydrationForSRSeries'],\n cond: 'shouldIgnoreHydrationForSR',\n },\n ],\n onError: {\n target: 'idle',\n },\n },\n },\n hydrateStructuredReport: {\n invoke: {\n src: 'hydrateStructuredReport',\n onDone: [\n {\n target: 'tracking',\n actions: [\n 'setTrackedStudyAndMultipleSeries',\n 'jumpToFirstMeasurementInActiveViewport',\n 'setIsDirtyToClean',\n ],\n },\n ],\n onError: {\n target: 'idle',\n },\n },\n },\n },\n strict: true,\n};\n\nconst defaultOptions = {\n services: {\n promptBeginTracking: (ctx, evt) => {\n // return { userResponse, StudyInstanceUID, SeriesInstanceUID }\n },\n promptTrackNewStudy: (ctx, evt) => {\n // return { userResponse, StudyInstanceUID, SeriesInstanceUID }\n },\n promptTrackNewSeries: (ctx, evt) => {\n // return { userResponse, StudyInstanceUID, SeriesInstanceUID }\n },\n },\n actions: {\n discardPreviouslyTrackedMeasurements: (ctx, evt) => {\n console.log('discardPreviouslyTrackedMeasurements: not implemented');\n },\n clearAllMeasurements: (ctx, evt) => {\n console.log('clearAllMeasurements: not implemented');\n },\n jumpToFirstMeasurementInActiveViewport: (ctx, evt) => {\n console.warn('jumpToFirstMeasurementInActiveViewport: not implemented');\n },\n showStructuredReportDisplaySetInActiveViewport: (ctx, evt) => {\n console.warn(\n 'showStructuredReportDisplaySetInActiveViewport: not implemented'\n );\n },\n clearContext: assign({\n trackedStudy: '',\n trackedSeries: [],\n ignoredSeries: [],\n prevTrackedStudy: '',\n prevTrackedSeries: [],\n prevIgnoredSeries: [],\n }),\n // Promise resolves w/ `evt.data.*`\n setTrackedStudyAndSeries: assign((ctx, evt) => ({\n prevTrackedStudy: ctx.trackedStudy,\n prevTrackedSeries: ctx.trackedSeries.slice(),\n prevIgnoredSeries: ctx.ignoredSeries.slice(),\n //\n trackedStudy: evt.data.StudyInstanceUID,\n trackedSeries: [evt.data.SeriesInstanceUID],\n ignoredSeries: [],\n })),\n setTrackedStudyAndMultipleSeries: assign((ctx, evt) => {\n const studyInstanceUID =\n evt.StudyInstanceUID || evt.data.StudyInstanceUID;\n const seriesInstanceUIDs =\n evt.SeriesInstanceUIDs || evt.data.SeriesInstanceUIDs;\n\n return {\n prevTrackedStudy: ctx.trackedStudy,\n prevTrackedSeries: ctx.trackedSeries.slice(),\n prevIgnoredSeries: ctx.ignoredSeries.slice(),\n //\n trackedStudy: studyInstanceUID,\n trackedSeries: [...ctx.trackedSeries, ...seriesInstanceUIDs],\n ignoredSeries: [],\n };\n }),\n setIsDirtyToClean: assign((ctx, evt) => ({\n isDirty: false,\n })),\n setIsDirty: assign((ctx, evt) => ({\n isDirty: true,\n })),\n ignoreSeries: assign((ctx, evt) => ({\n prevIgnoredSeries: [...ctx.ignoredSeries],\n ignoredSeries: [...ctx.ignoredSeries, evt.data.SeriesInstanceUID],\n })),\n ignoreHydrationForSRSeries: assign((ctx, evt) => ({\n ignoredSRSeriesForHydration: [\n ...ctx.ignoredSRSeriesForHydration,\n evt.data.srSeriesInstanceUID,\n ],\n })),\n addTrackedSeries: assign((ctx, evt) => ({\n prevTrackedSeries: [...ctx.trackedSeries],\n trackedSeries: [...ctx.trackedSeries, evt.data.SeriesInstanceUID],\n })),\n removeTrackedSeries: assign((ctx, evt) => ({\n prevTrackedSeries: ctx.trackedSeries\n .slice()\n .filter(ser => ser !== evt.SeriesInstanceUID),\n trackedSeries: ctx.trackedSeries\n .slice()\n .filter(ser => ser !== evt.SeriesInstanceUID),\n })),\n },\n guards: {\n // We set dirty any time we performan an action that:\n // - Tracks a new study\n // - Tracks a new series\n // - Adds a measurement to an already tracked study/series\n //\n // We set clean any time we restore from an SR\n //\n // This guard/condition is specific to \"new measurements\"\n // to make sure we only track dirty when the new measurement is specific\n // to a series we're already tracking\n //\n // tl;dr\n // Any report change, that is not a hydration of an existing report, should\n // result in a \"dirty\" report\n //\n // Where dirty means there would be \"loss of data\" if we blew away measurements\n // without creating a new SR.\n shouldSetDirty: (ctx, evt) => {\n return (\n // When would this happen?\n evt.SeriesInstanceUID === undefined ||\n ctx.trackedSeries.includes(evt.SeriesInstanceUID)\n );\n },\n shouldKillMachine: (ctx, evt) =>\n evt.data && evt.data.userResponse === RESPONSE.NO_NEVER,\n shouldAddSeries: (ctx, evt) =>\n evt.data && evt.data.userResponse === RESPONSE.ADD_SERIES,\n shouldSetStudyAndSeries: (ctx, evt) =>\n evt.data && evt.data.userResponse === RESPONSE.SET_STUDY_AND_SERIES,\n shouldAddIgnoredSeries: (ctx, evt) =>\n evt.data && evt.data.userResponse === RESPONSE.NO_NOT_FOR_SERIES,\n shouldPromptSaveReport: (ctx, evt) =>\n evt.data && evt.data.userResponse === RESPONSE.CREATE_REPORT,\n shouldIgnoreHydrationForSR: (ctx, evt) =>\n evt.data && evt.data.userResponse === RESPONSE.CANCEL,\n shouldSaveAndContinueWithSameReport: (ctx, evt) =>\n evt.data &&\n evt.data.userResponse === RESPONSE.CREATE_REPORT &&\n evt.data.isBackupSave === true,\n shouldSaveAndStartNewReport: (ctx, evt) =>\n evt.data &&\n evt.data.userResponse === RESPONSE.CREATE_REPORT &&\n evt.data.isBackupSave === false,\n shouldHydrateStructuredReport: (ctx, evt) =>\n evt.data && evt.data.userResponse === RESPONSE.HYDRATE_REPORT,\n // Has more than 1, or SeriesInstanceUID is not in list\n // --> Post removal would have non-empty trackedSeries array\n hasRemainingTrackedSeries: (ctx, evt) =>\n ctx.trackedSeries.length > 1 ||\n !ctx.trackedSeries.includes(evt.SeriesInstanceUID),\n hasNotIgnoredSRSeriesForHydration: (ctx, evt) => {\n return !ctx.ignoredSRSeriesForHydration.includes(evt.SeriesInstanceUID);\n },\n isNewStudy: (ctx, evt) =>\n !ctx.ignoredSeries.includes(evt.SeriesInstanceUID) &&\n ctx.trackedStudy !== evt.StudyInstanceUID,\n isNewSeries: (ctx, evt) =>\n !ctx.ignoredSeries.includes(evt.SeriesInstanceUID) &&\n !ctx.trackedSeries.includes(evt.SeriesInstanceUID),\n },\n};\n\nexport { defaultOptions, machineConfiguration };\n","const RESPONSE = {\n NO_NEVER: -1,\n CANCEL: 0,\n CREATE_REPORT: 1,\n ADD_SERIES: 2,\n SET_STUDY_AND_SERIES: 3,\n};\n\nfunction promptBeginTracking({ servicesManager, extensionManager }, ctx, evt) {\n const { uiViewportDialogService } = servicesManager.services;\n const { viewportIndex, StudyInstanceUID, SeriesInstanceUID } = evt;\n\n return new Promise(async function(resolve, reject) {\n let promptResult = await _askTrackMeasurements(\n uiViewportDialogService,\n viewportIndex\n );\n\n resolve({\n userResponse: promptResult,\n StudyInstanceUID,\n SeriesInstanceUID,\n viewportIndex,\n });\n });\n}\n\nfunction _askTrackMeasurements(uiViewportDialogService, viewportIndex) {\n return new Promise(function(resolve, reject) {\n const message = 'Track measurements for this series?';\n const actions = [\n {\n id: 'prompt-begin-tracking-cancel',\n type: 'cancel',\n text: 'No',\n value: RESPONSE.CANCEL,\n },\n {\n id: 'prompt-begin-tracking-no-do-not-ask-again',\n type: 'secondary',\n text: 'No, do not ask again',\n value: RESPONSE.NO_NEVER,\n },\n {\n id: 'prompt-begin-tracking-yes',\n type: 'primary',\n text: 'Yes',\n value: RESPONSE.SET_STUDY_AND_SERIES,\n },\n ];\n const onSubmit = result => {\n uiViewportDialogService.hide();\n resolve(result);\n };\n\n uiViewportDialogService.show({\n viewportIndex,\n id: 'measurement-tracking-prompt-begin-tracking',\n type: 'info',\n message,\n actions,\n onSubmit,\n onOutsideClick: () => {\n uiViewportDialogService.hide();\n resolve(RESPONSE.CANCEL);\n },\n });\n });\n}\n\nexport default promptBeginTracking;\n","const RESPONSE = {\n NO_NEVER: -1,\n CANCEL: 0,\n CREATE_REPORT: 1,\n ADD_SERIES: 2,\n SET_STUDY_AND_SERIES: 3,\n NO_NOT_FOR_SERIES: 4,\n};\n\nfunction promptTrackNewSeries({ servicesManager, extensionManager }, ctx, evt) {\n const { UIViewportDialogService } = servicesManager.services;\n const { viewportIndex, StudyInstanceUID, SeriesInstanceUID } = evt;\n\n return new Promise(async function(resolve, reject) {\n let promptResult = await _askShouldAddMeasurements(\n UIViewportDialogService,\n viewportIndex\n );\n\n if (promptResult === RESPONSE.CREATE_REPORT) {\n promptResult = ctx.isDirty\n ? await _askSaveDiscardOrCancel(UIViewportDialogService, viewportIndex)\n : RESPONSE.SET_STUDY_AND_SERIES;\n }\n\n resolve({\n userResponse: promptResult,\n StudyInstanceUID,\n SeriesInstanceUID,\n viewportIndex,\n isBackupSave: false,\n });\n });\n}\n\nfunction _askShouldAddMeasurements(uiViewportDialogService, viewportIndex) {\n return new Promise(function(resolve, reject) {\n const message =\n 'Do you want to add this measurement to the existing report?';\n const actions = [\n { type: 'cancel', text: 'Cancel', value: RESPONSE.CANCEL },\n {\n type: 'secondary',\n text: 'Create new report',\n value: RESPONSE.CREATE_REPORT,\n },\n {\n type: 'primary',\n text: 'Add to existing report',\n value: RESPONSE.ADD_SERIES,\n },\n ];\n const onSubmit = result => {\n uiViewportDialogService.hide();\n resolve(result);\n };\n\n uiViewportDialogService.show({\n viewportIndex,\n type: 'info',\n message,\n actions,\n onSubmit,\n onOutsideClick: () => {\n uiViewportDialogService.hide();\n resolve(RESPONSE.CANCEL);\n },\n });\n });\n}\n\nfunction _askSaveDiscardOrCancel(UIViewportDialogService, viewportIndex) {\n return new Promise(function(resolve, reject) {\n const message =\n 'You have existing tracked measurements. What would you like to do with your existing tracked measurements?';\n const actions = [\n { type: 'cancel', text: 'Cancel', value: RESPONSE.CANCEL },\n {\n type: 'secondary',\n text: 'Save',\n value: RESPONSE.CREATE_REPORT,\n },\n {\n type: 'primary',\n text: 'Discard',\n value: RESPONSE.SET_STUDY_AND_SERIES,\n },\n ];\n const onSubmit = result => {\n UIViewportDialogService.hide();\n resolve(result);\n };\n\n UIViewportDialogService.show({\n viewportIndex,\n type: 'warning',\n message,\n actions,\n onSubmit,\n onOutsideClick: () => {\n UIViewportDialogService.hide();\n resolve(RESPONSE.CANCEL);\n },\n });\n });\n}\n\nexport default promptTrackNewSeries;\n","const RESPONSE = {\n NO_NEVER: -1,\n CANCEL: 0,\n CREATE_REPORT: 1,\n ADD_SERIES: 2,\n SET_STUDY_AND_SERIES: 3,\n NO_NOT_FOR_SERIES: 4,\n};\n\nfunction promptTrackNewStudy({ servicesManager, extensionManager }, ctx, evt) {\n const { UIViewportDialogService } = servicesManager.services;\n const { viewportIndex, StudyInstanceUID, SeriesInstanceUID } = evt;\n\n return new Promise(async function(resolve, reject) {\n let promptResult = await _askTrackMeasurements(\n UIViewportDialogService,\n viewportIndex\n );\n\n if (promptResult === RESPONSE.SET_STUDY_AND_SERIES) {\n promptResult = ctx.isDirty\n ? await _askSaveDiscardOrCancel(UIViewportDialogService, viewportIndex)\n : RESPONSE.SET_STUDY_AND_SERIES;\n }\n\n resolve({\n userResponse: promptResult,\n StudyInstanceUID,\n SeriesInstanceUID,\n viewportIndex,\n isBackupSave: false,\n });\n });\n}\n\nfunction _askTrackMeasurements(UIViewportDialogService, viewportIndex) {\n return new Promise(function(resolve, reject) {\n const message = 'Track measurements for this series?';\n const actions = [\n { type: 'cancel', text: 'No', value: RESPONSE.CANCEL },\n {\n type: 'secondary',\n text: 'No, do not ask again for this series',\n value: RESPONSE.NO_NOT_FOR_SERIES,\n },\n {\n type: 'primary',\n text: 'Yes',\n value: RESPONSE.SET_STUDY_AND_SERIES,\n },\n ];\n const onSubmit = result => {\n UIViewportDialogService.hide();\n resolve(result);\n };\n\n UIViewportDialogService.show({\n viewportIndex,\n type: 'info',\n message,\n actions,\n onSubmit,\n onOutsideClick: () => {\n UIViewportDialogService.hide();\n resolve(RESPONSE.CANCEL);\n },\n });\n });\n}\n\nfunction _askSaveDiscardOrCancel(UIViewportDialogService, viewportIndex) {\n return new Promise(function(resolve, reject) {\n const message =\n 'Measurements cannot span across multiple studies. Do you want to save your tracked measurements?';\n const actions = [\n { type: 'cancel', text: 'Cancel', value: RESPONSE.CANCEL },\n {\n type: 'secondary',\n text: 'No, discard previously tracked series & measurements',\n value: RESPONSE.SET_STUDY_AND_SERIES,\n },\n {\n type: 'primary',\n text: 'Yes',\n value: RESPONSE.CREATE_REPORT,\n },\n ];\n const onSubmit = result => {\n UIViewportDialogService.hide();\n resolve(result);\n };\n\n UIViewportDialogService.show({\n viewportIndex,\n type: 'warning',\n message,\n actions,\n onSubmit,\n onOutsideClick: () => {\n UIViewportDialogService.hide();\n resolve(RESPONSE.CANCEL);\n },\n });\n });\n}\n\nexport default promptTrackNewStudy;\n","import React from 'react';\nimport { DicomMetadataStore } from '@ohif/core';\n\n/**\n *\n * @param {*} servicesManager\n * @param {*} dataSource\n * @param {*} measurements\n * @param {*} options\n * @returns {string[]} displaySetInstanceUIDs\n */\nasync function createReportAsync(\n servicesManager,\n commandsManager,\n dataSource,\n measurements,\n options\n) {\n const {\n displaySetService,\n uiNotificationService,\n uiDialogService,\n } = servicesManager.services;\n const loadingDialogId = uiDialogService.create({\n showOverlay: true,\n isDraggable: false,\n centralize: true,\n // TODO: Create a loading indicator component + zeplin design?\n content: Loading,\n });\n\n try {\n const naturalizedReport = await commandsManager.runCommand(\n 'storeMeasurements',\n {\n measurementData: measurements,\n dataSource,\n additionalFindingTypes: ['ArrowAnnotate'],\n options,\n },\n 'CORNERSTONE_STRUCTURED_REPORT'\n );\n\n // The \"Mode\" route listens for DicomMetadataStore changes\n // When a new instance is added, it listens and\n // automatically calls makeDisplaySets\n DicomMetadataStore.addInstances([naturalizedReport], true);\n\n const displaySetInstanceUID = displaySetService.getMostRecentDisplaySet();\n\n uiNotificationService.show({\n title: 'Create Report',\n message: 'Measurements saved successfully',\n type: 'success',\n });\n\n return [displaySetInstanceUID];\n } catch (error) {\n uiNotificationService.show({\n title: 'Create Report',\n message: error.message || 'Failed to store measurements',\n type: 'error',\n });\n } finally {\n uiDialogService.dismiss({ id: loadingDialogId });\n }\n}\n\nfunction Loading() {\n return <div className=\"text-primary-active\">Loading...</div>;\n}\n\nexport default createReportAsync;\n","const RESPONSE = {\n NO_NEVER: -1,\n CANCEL: 0,\n CREATE_REPORT: 1,\n ADD_SERIES: 2,\n SET_STUDY_AND_SERIES: 3,\n NO_NOT_FOR_SERIES: 4,\n};\n\nexport default RESPONSE;\n","const MIN_SR_SERIES_NUMBER = 4700;\n\nexport default function getNextSRSeriesNumber(displaySetService) {\n const activeDisplaySets = displaySetService.getActiveDisplaySets();\n const srDisplaySets = activeDisplaySets.filter(ds => ds.Modality === 'SR');\n const srSeriesNumbers = srDisplaySets.map(ds => ds.SeriesNumber);\n const maxSeriesNumber = Math.max(...srSeriesNumbers, MIN_SR_SERIES_NUMBER);\n\n return maxSeriesNumber + 1;\n}\n","import createReportAsync from './../../_shared/createReportAsync';\nimport createReportDialogPrompt from '../../_shared/createReportDialogPrompt';\nimport getNextSRSeriesNumber from '../../_shared/getNextSRSeriesNumber';\nimport RESPONSE from '../../_shared/PROMPT_RESPONSES';\n\nfunction promptSaveReport(\n { servicesManager, commandsManager, extensionManager },\n ctx,\n evt\n) {\n const {\n uiDialogService,\n measurementService,\n displaySetService,\n } = servicesManager.services;\n const viewportIndex =\n evt.viewportIndex === undefined\n ? evt.data.viewportIndex\n : evt.viewportIndex;\n const isBackupSave =\n evt.isBackupSave === undefined ? evt.data.isBackupSave : evt.isBackupSave;\n const StudyInstanceUID = evt?.data?.StudyInstanceUID;\n const SeriesInstanceUID = evt?.data?.SeriesInstanceUID;\n\n const { trackedStudy, trackedSeries } = ctx;\n let displaySetInstanceUIDs;\n\n return new Promise(async function(resolve, reject) {\n // TODO: Fallback if (uiDialogService) {\n const promptResult = await createReportDialogPrompt(uiDialogService);\n\n if (promptResult.action === RESPONSE.CREATE_REPORT) {\n const dataSources = extensionManager.getDataSources();\n const dataSource = dataSources[0];\n const measurements = measurementService.getMeasurements();\n const trackedMeasurements = measurements.filter(\n m =>\n trackedStudy === m.referenceStudyUID &&\n trackedSeries.includes(m.referenceSeriesUID)\n );\n\n const SeriesDescription =\n // isUndefinedOrEmpty\n promptResult.value === undefined || promptResult.value === ''\n ? 'Research Derived Series' // default\n : promptResult.value; // provided value\n\n const SeriesNumber = getNextSRSeriesNumber(displaySetService);\n\n displaySetInstanceUIDs = await createReportAsync(\n servicesManager,\n commandsManager,\n dataSource,\n trackedMeasurements,\n {\n SeriesDescription,\n SeriesNumber,\n }\n );\n } else if (promptResult.action === RESPONSE.CANCEL) {\n // Do nothing\n }\n\n resolve({\n userResponse: promptResult.action,\n createdDisplaySetInstanceUIDs: displaySetInstanceUIDs,\n StudyInstanceUID,\n SeriesInstanceUID,\n viewportIndex,\n isBackupSave,\n });\n });\n}\n\nexport default promptSaveReport;\n","/* eslint-disable react/display-name */\nimport React from 'react';\nimport { Dialog, Input } from '@ohif/ui';\nimport RESPONSE from './PROMPT_RESPONSES';\n\nexport default function createReportDialogPrompt(uiDialogService) {\n return new Promise(function(resolve, reject) {\n let dialogId = undefined;\n\n const _handleClose = () => {\n // Dismiss dialog\n uiDialogService.dismiss({ id: dialogId });\n // Notify of cancel action\n resolve({ action: RESPONSE.CANCEL, value: undefined });\n };\n\n /**\n *\n * @param {string} param0.action - value of action performed\n * @param {string} param0.value - value from input field\n */\n const _handleFormSubmit = ({ action, value }) => {\n uiDialogService.dismiss({ id: dialogId });\n switch (action.id) {\n case 'save':\n resolve({ action: RESPONSE.CREATE_REPORT, value: value.label });\n break;\n case 'cancel':\n resolve({ action: RESPONSE.CANCEL, value: undefined });\n break;\n }\n };\n\n dialogId = uiDialogService.create({\n centralize: true,\n isDraggable: false,\n content: Dialog,\n useLastPosition: false,\n showOverlay: true,\n contentProps: {\n title: 'Provide a name for your report',\n value: { label: '' },\n noCloseButton: true,\n onClose: _handleClose,\n actions: [\n { id: 'cancel', text: 'Cancel', type: 'primary' },\n { id: 'save', text: 'Save', type: 'secondary' },\n ],\n // TODO: Should be on button press...\n onSubmit: _handleFormSubmit,\n body: ({ value, setValue }) => {\n const onChangeHandler = event => {\n event.persist();\n setValue(value => ({ ...value, label: event.target.value }));\n };\n const onKeyPressHandler = event => {\n if (event.key === 'Enter') {\n uiDialogService.dismiss({ id: dialogId });\n resolve({ action: RESPONSE.CREATE_REPORT, value: value.label });\n }\n };\n return (\n <div className=\"p-4 bg-primary-dark\">\n <Input\n autoFocus\n className=\"mt-2 bg-black border-primary-main\"\n type=\"text\"\n containerClassName=\"mr-2\"\n value={value.label}\n onChange={onChangeHandler}\n onKeyPress={onKeyPressHandler}\n />\n </div>\n );\n },\n },\n });\n });\n}\n","import { hydrateStructuredReport } from '@ohif/extension-cornerstone-dicom-sr';\n\nconst RESPONSE = {\n NO_NEVER: -1,\n CANCEL: 0,\n CREATE_REPORT: 1,\n ADD_SERIES: 2,\n SET_STUDY_AND_SERIES: 3,\n NO_NOT_FOR_SERIES: 4,\n HYDRATE_REPORT: 5,\n};\n\nfunction promptHydrateStructuredReport(\n { servicesManager, extensionManager },\n ctx,\n evt\n) {\n const {\n uiViewportDialogService,\n displaySetService,\n } = servicesManager.services;\n const { viewportIndex, displaySetInstanceUID } = evt;\n const srDisplaySet = displaySetService.getDisplaySetByUID(\n displaySetInstanceUID\n );\n\n return new Promise(async function(resolve, reject) {\n const promptResult = await _askTrackMeasurements(\n uiViewportDialogService,\n viewportIndex\n );\n\n // Need to do action here... So we can set state...\n let StudyInstanceUID, SeriesInstanceUIDs;\n\n if (promptResult === RESPONSE.HYDRATE_REPORT) {\n console.warn('!! HYDRATING STRUCTURED REPORT');\n const hydrationResult = hydrateStructuredReport(\n { servicesManager, extensionManager },\n displaySetInstanceUID\n );\n\n StudyInstanceUID = hydrationResult.StudyInstanceUID;\n SeriesInstanceUIDs = hydrationResult.SeriesInstanceUIDs;\n }\n\n resolve({\n userResponse: promptResult,\n displaySetInstanceUID: evt.displaySetInstanceUID,\n srSeriesInstanceUID: srDisplaySet.SeriesInstanceUID,\n viewportIndex,\n StudyInstanceUID,\n SeriesInstanceUIDs,\n });\n });\n}\n\nfunction _askTrackMeasurements(uiViewportDialogService, viewportIndex) {\n return new Promise(function(resolve, reject) {\n const message =\n 'Do you want to continue tracking measurements for this study?';\n const actions = [\n {\n type: 'secondary',\n text: 'No',\n value: RESPONSE.CANCEL,\n },\n {\n type: 'primary',\n text: 'Yes',\n value: RESPONSE.HYDRATE_REPORT,\n },\n ];\n const onSubmit = result => {\n uiViewportDialogService.hide();\n resolve(result);\n };\n\n uiViewportDialogService.show({\n viewportIndex,\n type: 'info',\n message,\n actions,\n onSubmit,\n onOutsideClick: () => {\n uiViewportDialogService.hide();\n resolve(RESPONSE.CANCEL);\n },\n });\n });\n}\n\nexport default promptHydrateStructuredReport;\n","import { hydrateStructuredReport as baseHydrateStructuredReport } from '@ohif/extension-cornerstone-dicom-sr';\n\nfunction hydrateStructuredReport(\n { servicesManager, extensionManager },\n ctx,\n evt\n) {\n const { displaySetService } = servicesManager.services;\n const { viewportIndex, displaySetInstanceUID } = evt;\n const srDisplaySet = displaySetService.getDisplaySetByUID(\n displaySetInstanceUID\n );\n\n return new Promise((resolve, reject) => {\n const hydrationResult = baseHydrateStructuredReport(\n { servicesManager, extensionManager },\n displaySetInstanceUID\n );\n\n const StudyInstanceUID = hydrationResult.StudyInstanceUID;\n const SeriesInstanceUIDs = hydrationResult.SeriesInstanceUIDs;\n\n resolve({\n displaySetInstanceUID: evt.displaySetInstanceUID,\n srSeriesInstanceUID: srDisplaySet.SeriesInstanceUID,\n viewportIndex,\n StudyInstanceUID,\n SeriesInstanceUIDs,\n });\n });\n}\n\nexport default hydrateStructuredReport;\n","import React, { useContext, useEffect } from 'react';\nimport PropTypes from 'prop-types';\nimport { Machine } from 'xstate';\nimport { useMachine } from '@xstate/react';\nimport { useViewportGrid } from '@ohif/ui';\nimport {\n machineConfiguration,\n defaultOptions,\n} from './measurementTrackingMachine';\nimport promptBeginTracking from './promptBeginTracking';\nimport promptTrackNewSeries from './promptTrackNewSeries';\nimport promptTrackNewStudy from './promptTrackNewStudy';\nimport promptSaveReport from './promptSaveReport';\nimport promptHydrateStructuredReport from './promptHydrateStructuredReport';\nimport hydrateStructuredReport from './hydrateStructuredReport';\n\nconst TrackedMeasurementsContext = React.createContext();\nTrackedMeasurementsContext.displayName = 'TrackedMeasurementsContext';\nconst useTrackedMeasurements = () => useContext(TrackedMeasurementsContext);\n\nconst SR_SOPCLASSHANDLERID =\n '@ohif/extension-cornerstone-dicom-sr.sopClassHandlerModule.dicom-sr';\n\n/**\n *\n * @param {*} param0\n */\nfunction TrackedMeasurementsContextProvider(\n { servicesManager, commandsManager, extensionManager }, // Bound by consumer\n { children } // Component props\n) {\n const [viewportGrid, viewportGridService] = useViewportGrid();\n const { activeViewportIndex, viewports } = viewportGrid;\n const { measurementService, displaySetService } = servicesManager.services;\n\n const machineOptions = Object.assign({}, defaultOptions);\n machineOptions.actions = Object.assign({}, machineOptions.actions, {\n jumpToFirstMeasurementInActiveViewport: (ctx, evt) => {\n const { trackedStudy, trackedSeries } = ctx;\n const measurements = measurementService.getMeasurements();\n const trackedMeasurements = measurements.filter(\n m =>\n trackedStudy === m.referenceStudyUID &&\n trackedSeries.includes(m.referenceSeriesUID)\n );\n\n console.log(\n 'jumping to measurement reset viewport',\n viewportGrid.activeViewportIndex,\n trackedMeasurements[0]\n );\n\n const referencedDisplaySetUID =\n trackedMeasurements[0].displaySetInstanceUID;\n const referencedDisplaySet = displaySetService.getDisplaySetByUID(\n referencedDisplaySetUID\n );\n\n const referencedImages = referencedDisplaySet.images;\n const isVolumeIdReferenced = referencedImages[0].imageId.startsWith(\n 'volumeId'\n );\n\n const measurementData = trackedMeasurements[0].data;\n\n let imageIndex = 0;\n if (!isVolumeIdReferenced && measurementData) {\n // if it is imageId referenced find the index of the imageId, we don't have\n // support for volumeId referenced images yet\n imageIndex = referencedImages.findIndex(image => {\n const imageIdToUse = Object.keys(measurementData)[0].substring(8);\n return image.imageId === imageIdToUse;\n });\n\n if (imageIndex === -1) {\n console.warn(\n 'Could not find image index for tracked measurement, using 0'\n );\n imageIndex = 0;\n }\n }\n\n viewportGridService.setDisplaySetsForViewport({\n viewportIndex: viewportGrid.activeViewportIndex,\n displaySetInstanceUIDs: [referencedDisplaySetUID],\n viewportOptions: {\n initialImageOptions: {\n index: imageIndex,\n },\n },\n });\n },\n showStructuredReportDisplaySetInActiveViewport: (ctx, evt) => {\n if (evt.data.createdDisplaySetInstanceUIDs.length > 0) {\n const StructuredReportDisplaySetInstanceUID =\n evt.data.createdDisplaySetInstanceUIDs[0].displaySetInstanceUID;\n\n viewportGridService.setDisplaySetsForViewport({\n viewportIndex: evt.data.viewportIndex,\n displaySetInstanceUIDs: [StructuredReportDisplaySetInstanceUID],\n });\n }\n },\n discardPreviouslyTrackedMeasurements: (ctx, evt) => {\n const measurements = measurementService.getMeasurements();\n const filteredMeasurements = measurements.filter(ms =>\n ctx.prevTrackedSeries.includes(ms.referenceSeriesUID)\n );\n const measurementIds = filteredMeasurements.map(fm => fm.id);\n\n for (let i = 0; i < measurementIds.length; i++) {\n measurementService.remove(measurementIds[i]);\n }\n },\n clearAllMeasurements: (ctx, evt) => {\n const measurements = measurementService.getMeasurements();\n const measurementIds = measurements.map(fm => fm.uid);\n\n for (let i = 0; i < measurementIds.length; i++) {\n measurementService.remove(measurementIds[i]);\n }\n },\n });\n machineOptions.services = Object.assign({}, machineOptions.services, {\n promptBeginTracking: promptBeginTracking.bind(null, {\n servicesManager,\n extensionManager,\n }),\n promptTrackNewSeries: promptTrackNewSeries.bind(null, {\n servicesManager,\n extensionManager,\n }),\n promptTrackNewStudy: promptTrackNewStudy.bind(null, {\n servicesManager,\n extensionManager,\n }),\n promptSaveReport: promptSaveReport.bind(null, {\n servicesManager,\n commandsManager,\n extensionManager,\n }),\n promptHydrateStructuredReport: promptHydrateStructuredReport.bind(null, {\n servicesManager,\n extensionManager,\n }),\n hydrateStructuredReport: hydrateStructuredReport.bind(null, {\n servicesManager,\n extensionManager,\n }),\n });\n\n // TODO: IMPROVE\n // - Add measurement_updated to cornerstone; debounced? (ext side, or consumption?)\n // - Friendlier transition/api in front of measurementTracking machine?\n // - Blocked: viewport overlay shouldn't clip when resized\n // TODO: PRIORITY\n // - Fix \"ellipses\" series description dynamic truncate length\n // - Fix viewport border resize\n // - created/destroyed hooks for extensions (cornerstone measurement subscriptions in it's `init`)\n\n const measurementTrackingMachine = Machine(\n machineConfiguration,\n machineOptions\n );\n\n const [\n trackedMeasurements,\n sendTrackedMeasurementsEvent,\n trackedMeasurementsService,\n ] = useMachine(measurementTrackingMachine);\n\n // ~~ Listen for changes to ViewportGrid for potential SRs hung in panes when idle\n useEffect(() => {\n if (viewports.length > 0) {\n const activeViewport = viewports[activeViewportIndex];\n\n if (!activeViewport || !activeViewport?.displaySetInstanceUIDs?.length) {\n return;\n }\n\n // Todo: Getting the first displaySetInstanceUID is wrong, but we don't have\n // tracking fusion viewports yet. This should change when we do.\n const { displaySetService } = servicesManager.services;\n const displaySet = displaySetService.getDisplaySetByUID(\n activeViewport.displaySetInstanceUIDs[0]\n );\n\n if (!displaySet) {\n return;\n }\n\n // If this is an SR produced by our SR SOPClassHandler,\n // and it hasn't been loaded yet, do that now so we\n // can check if it can be rehydrated or not.\n //\n // Note: This happens:\n // - If the viewport is not currently an OHIFCornerstoneSRViewport\n // - If the displaySet has never been hung\n //\n // Otherwise, the displaySet will be loaded by the useEffect handler\n // listening to displaySet changes inside OHIFCornerstoneSRViewport.\n // The issue here is that this handler in TrackedMeasurementsContext\n // ends up occurring before the Viewport is created, so the displaySet\n // is not loaded yet, and isRehydratable is undefined unless we call load().\n if (\n displaySet.SOPClassHandlerId === SR_SOPCLASSHANDLERID &&\n !displaySet.isLoaded &&\n displaySet.load\n ) {\n displaySet.load();\n }\n\n // Magic string\n // load function added by our sopClassHandler module\n if (\n displaySet.SOPClassHandlerId === SR_SOPCLASSHANDLERID &&\n displaySet.isRehydratable === true\n ) {\n console.log('sending event...', trackedMeasurements);\n sendTrackedMeasurementsEvent('PROMPT_HYDRATE_SR', {\n displaySetInstanceUID: displaySet.displaySetInstanceUID,\n SeriesInstanceUID: displaySet.SeriesInstanceUID,\n viewportIndex: activeViewportIndex,\n });\n }\n }\n }, [\n activeViewportIndex,\n sendTrackedMeasurementsEvent,\n servicesManager.services,\n viewports,\n ]);\n\n return (\n <TrackedMeasurementsContext.Provider\n value={[trackedMeasurements, sendTrackedMeasurementsEvent]}\n >\n {children}\n </TrackedMeasurementsContext.Provider>\n );\n}\n\nTrackedMeasurementsContextProvider.propTypes = {\n children: PropTypes.oneOf([PropTypes.func, PropTypes.node]),\n servicesManager: PropTypes.object.isRequired,\n commandsManager: PropTypes.object.isRequired,\n extensionManager: PropTypes.object.isRequired,\n};\n\nexport {\n TrackedMeasurementsContext,\n TrackedMeasurementsContextProvider,\n useTrackedMeasurements,\n};\n","import {\n TrackedMeasurementsContext,\n TrackedMeasurementsContextProvider,\n useTrackedMeasurements,\n} from './contexts';\n\nfunction getContextModule({\n servicesManager,\n extensionManager,\n commandsManager,\n}) {\n const BoundTrackedMeasurementsContextProvider = TrackedMeasurementsContextProvider.bind(\n null,\n { servicesManager, extensionManager, commandsManager }\n );\n\n return [\n {\n name: 'TrackedMeasurementsContext',\n context: TrackedMeasurementsContext,\n provider: BoundTrackedMeasurementsContextProvider,\n },\n ];\n}\n\nexport { useTrackedMeasurements };\nexport default getContextModule;\n","import React, { useState, useEffect, useCallback } from 'react';\nimport PropTypes from 'prop-types';\nimport OHIF, { utils } from '@ohif/core';\n\nimport { ViewportActionBar, Tooltip, Icon } from '@ohif/ui';\n\nimport { useTranslation } from 'react-i18next';\n\nimport { annotation } from '@cornerstonejs/tools';\nimport { useTrackedMeasurements } from './../getContextModule';\nimport { BaseVolumeViewport, Enums } from '@cornerstonejs/core';\n\nconst { formatDate } = utils;\n\nfunction TrackedCornerstoneViewport(props) {\n const {\n displaySets,\n viewportIndex,\n viewportLabel,\n servicesManager,\n extensionManager,\n viewportOptions,\n } = props;\n\n const { t } = useTranslation('TrackedViewport');\n\n const {\n measurementService,\n cornerstoneViewportService,\n } = servicesManager.services;\n\n // Todo: handling more than one displaySet on the same viewport\n const displaySet = displaySets[0];\n\n const [trackedMeasurements] = useTrackedMeasurements();\n const [isTracked, setIsTracked] = useState(false);\n const [trackedMeasurementUID, setTrackedMeasurementUID] = useState(null);\n const [viewportElem, setViewportElem] = useState(null);\n\n const { trackedSeries } = trackedMeasurements.context;\n const viewportId = viewportOptions.viewportId;\n\n const {\n SeriesDate,\n SeriesDescription,\n SeriesInstanceUID,\n SeriesNumber,\n } = displaySet;\n\n const {\n PatientID,\n PatientName,\n PatientSex,\n PatientAge,\n SliceThickness,\n SpacingBetweenSlices,\n ManufacturerModelName,\n } = displaySet.images[0];\n\n const updateIsTracked = useCallback(() => {\n const viewport = cornerstoneViewportService.getCornerstoneViewportByIndex(\n viewportIndex\n );\n\n if (viewport instanceof BaseVolumeViewport) {\n // A current image id will only exist for volume viewports that can have measurements tracked.\n // Typically these are those volume viewports for the series of acquisition.\n const currentImageId = viewport?.getCurrentImageId();\n\n if (!currentImageId) {\n if (isTracked) {\n setIsTracked(false);\n }\n return;\n }\n }\n\n if (trackedSeries.includes(SeriesInstanceUID) !== isTracked) {\n setIsTracked(!isTracked);\n }\n }, [isTracked, trackedMeasurements, viewportIndex, SeriesInstanceUID]);\n\n const onElementEnabled = useCallback(\n evt => {\n if (evt.detail.element !== viewportElem) {\n // The VOLUME_VIEWPORT_NEW_VOLUME event allows updateIsTracked to reliably fetch the image id for a volume viewport.\n evt.detail.element?.addEventListener(\n Enums.Events.VOLUME_VIEWPORT_NEW_VOLUME,\n updateIsTracked\n );\n setViewportElem(evt.detail.element);\n }\n },\n [updateIsTracked, viewportElem]\n );\n\n const onElementDisabled = useCallback(() => {\n viewportElem?.removeEventListener(\n Enums.Events.VOLUME_VIEWPORT_NEW_VOLUME,\n updateIsTracked\n );\n }, [updateIsTracked, viewportElem]);\n\n useEffect(updateIsTracked, [updateIsTracked]);\n\n useEffect(() => {\n const { unsubscribe } = cornerstoneViewportService.subscribe(\n cornerstoneViewportService.EVENTS.VIEWPORT_DATA_CHANGED,\n props => {\n if (props.viewportIndex !== viewportIndex) {\n return;\n }\n\n updateIsTracked();\n }\n );\n\n return () => {\n unsubscribe();\n };\n }, [updateIsTracked, viewportIndex]);\n\n useEffect(() => {\n if (isTracked) {\n annotation.config.style.setViewportToolStyles(viewportId, {\n global: {\n lineDash: '',\n },\n });\n\n cornerstoneViewportService\n .getRenderingEngine()\n .renderViewport(viewportId);\n\n return;\n }\n\n annotation.config.style.setViewportToolStyles(viewportId, {\n global: {\n lineDash: '4,4',\n },\n });\n\n cornerstoneViewportService.getRenderingEngine().renderViewport(viewportId);\n\n return () => {\n annotation.config.style.setViewportToolStyles(viewportId, {});\n };\n }, [isTracked]);\n\n function switchMeasurement(direction) {\n const newTrackedMeasurementUID = _getNextMeasurementUID(\n direction,\n servicesManager,\n trackedMeasurementUID,\n trackedMeasurements\n );\n\n if (!newTrackedMeasurementUID) {\n return;\n }\n\n setTrackedMeasurementUID(newTrackedMeasurementUID);\n\n measurementService.jumpToMeasurement(\n viewportIndex,\n newTrackedMeasurementUID\n );\n }\n\n const getCornerstoneViewport = () => {\n const { component: Component } = extensionManager.getModuleEntry(\n '@ohif/extension-cornerstone.viewportModule.cornerstone'\n );\n\n return (\n <Component\n {...props}\n onElementEnabled={onElementEnabled}\n onElementDisabled={onElementDisabled}\n />\n );\n };\n\n return (\n <>\n <ViewportActionBar\n onDoubleClick={evt => {\n evt.stopPropagation();\n evt.preventDefault();\n }}\n useAltStyling={isTracked}\n onArrowsClick={direction => switchMeasurement(direction)}\n getStatusComponent={() => _getStatusComponent(isTracked)}\n studyData={{\n label: viewportLabel,\n studyDate: formatDate(SeriesDate), // TODO: This is series date. Is that ok?\n currentSeries: SeriesNumber, // TODO - switch entire currentSeries to be UID based or actual position based\n seriesDescription: SeriesDescription,\n patientInformation: {\n patientName: PatientName ? OHIF.utils.formatPN(PatientName) : '',\n patientSex: PatientSex || '',\n patientAge: PatientAge || '',\n MRN: PatientID || '',\n thickness: SliceThickness\n ? `${parseFloat(SliceThickness).toFixed(2)}mm`\n : '',\n spacing:\n SpacingBetweenSlices !== undefined\n ? `${parseFloat(SpacingBetweenSlices).toFixed(2)}mm`\n : '',\n scanner: ManufacturerModelName || '',\n },\n }}\n />\n {/* TODO: Viewport interface to accept stack or layers of content like this? */}\n <div className=\"relative flex flex-row w-full h-full overflow-hidden\">\n {getCornerstoneViewport()}\n </div>\n </>\n );\n}\n\nTrackedCornerstoneViewport.propTypes = {\n displaySets: PropTypes.arrayOf(PropTypes.object.isRequired).isRequired,\n viewportIndex: PropTypes.number.isRequired,\n dataSource: PropTypes.object,\n children: PropTypes.node,\n customProps: PropTypes.object,\n};\n\nTrackedCornerstoneViewport.defaultProps = {\n customProps: {},\n};\n\nfunction _getNextMeasurementUID(\n direction,\n servicesManager,\n trackedMeasurementId,\n trackedMeasurements\n) {\n const { measurementService, viewportGridService } = servicesManager.services;\n const measurements = measurementService.getMeasurements();\n\n const { activeViewportIndex, viewports } = viewportGridService.getState();\n const {\n displaySetInstanceUIDs: activeViewportDisplaySetInstanceUIDs,\n } = viewports[activeViewportIndex];\n\n const { trackedSeries } = trackedMeasurements.context;\n\n // Get the potentially trackable measurements for the series of the\n // active viewport.\n // The measurements to jump between are the same\n // regardless if this series is tracked or not.\n\n const filteredMeasurements = measurements.filter(\n m =>\n trackedSeries.includes(m.referenceSeriesUID) &&\n activeViewportDisplaySetInstanceUIDs.includes(m.displaySetInstanceUID)\n );\n\n if (!filteredMeasurements.length) {\n // No measurements on this series.\n return;\n }\n\n const measurementCount = filteredMeasurements.length;\n\n const uids = filteredMeasurements.map(fm => fm.uid);\n let measurementIndex = uids.findIndex(uid => uid === trackedMeasurementId);\n\n if (measurementIndex === -1) {\n // Not tracking a measurement, or previous measurement now deleted, revert to 0.\n measurementIndex = 0;\n } else {\n if (direction === 'left') {\n measurementIndex--;\n\n if (measurementIndex < 0) {\n measurementIndex = measurementCount - 1;\n }\n } else if (direction === 'right') {\n measurementIndex++;\n\n if (measurementIndex === measurementCount) {\n measurementIndex = 0;\n }\n }\n }\n\n const newTrackedMeasurementId = uids[measurementIndex];\n\n return newTrackedMeasurementId;\n}\n\nfunction _getStatusComponent(isTracked) {\n const trackedIcon = isTracked ? 'status-tracked' : 'status-untracked';\n\n return (\n <div className=\"relative\">\n <Tooltip\n position=\"bottom-left\"\n content={\n <div className=\"flex py-2\">\n <div className=\"flex pt-1\">\n <Icon name=\"info-link\" className=\"w-4 text-primary-main\" />\n </div>\n <div className=\"flex ml-4\">\n <span className=\"text-base text-common-light\">\n {isTracked ? (\n <>\n Series is\n <span className=\"font-bold text-white\"> tracked</span> and\n can be viewed <br /> in the measurement panel\n </>\n ) : (\n <>\n Measurements for\n <span className=\"font-bold text-white\"> untracked </span>\n series <br /> will not be shown in the <br /> measurements\n panel\n </>\n )}\n </span>\n </div>\n </div>\n }\n >\n <Icon name={trackedIcon} className=\"text-primary-light\" />\n </Tooltip>\n </div>\n );\n}\n\nexport default TrackedCornerstoneViewport;\n","/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the `TypeError` message for \"Functions\" methods. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n return root.Date.now();\n};\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n result = wait - timeSinceLastCall;\n\n return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && objectToString.call(value) == symbolTag);\n}\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = debounce;\n","/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\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'use strict';\n\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n\nfunction emptyFunction() {}\nfunction emptyFunctionWithReset() {}\nemptyFunctionWithReset.resetWarningCache = emptyFunction;\n\nmodule.exports = function() {\n function shim(props, propName, componentName, location, propFullName, secret) {\n if (secret === ReactPropTypesSecret) {\n // It is still safe when called from React.\n return;\n }\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use PropTypes.checkPropTypes() to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n };\n shim.isRequired = shim;\n function getShim() {\n return shim;\n };\n // Important!\n // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n var ReactPropTypes = {\n array: shim,\n bigint: shim,\n bool: shim,\n func: shim,\n number: shim,\n object: shim,\n string: shim,\n symbol: shim,\n\n any: shim,\n arrayOf: getShim,\n element: shim,\n elementType: shim,\n instanceOf: getShim,\n node: shim,\n objectOf: getShim,\n oneOf: getShim,\n oneOfType: getShim,\n shape: getShim,\n exact: getShim,\n\n checkPropTypes: emptyFunctionWithReset,\n resetWarningCache: emptyFunction\n };\n\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\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\nif (process.env.NODE_ENV !== 'production') {\n var ReactIs = require('react-is');\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);\n} else {\n // By explicitly using `prop-types` you are opting into new production behavior.\n // http://fb.me/prop-types-in-prod\n module.exports = require('./factoryWithThrowingShims')();\n}\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\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'use strict';\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n","/** @license React v17.0.2\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=require(\"object-assign\"),n=60103,p=60106;exports.Fragment=60107;exports.StrictMode=60108;exports.Profiler=60114;var q=60109,r=60110,t=60112;exports.Suspense=60113;var u=60115,v=60116;\nif(\"function\"===typeof Symbol&&Symbol.for){var w=Symbol.for;n=w(\"react.element\");p=w(\"react.portal\");exports.Fragment=w(\"react.fragment\");exports.StrictMode=w(\"react.strict_mode\");exports.Profiler=w(\"react.profiler\");q=w(\"react.provider\");r=w(\"react.context\");t=w(\"react.forward_ref\");exports.Suspense=w(\"react.suspense\");u=w(\"react.memo\");v=w(\"react.lazy\")}var x=\"function\"===typeof Symbol&&Symbol.iterator;\nfunction y(a){if(null===a||\"object\"!==typeof a)return null;a=x&&a[x]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}function z(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;c<arguments.length;c++)b+=\"&args[]=\"+encodeURIComponent(arguments[c]);return\"Minified React error #\"+a+\"; visit \"+b+\" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.\"}\nvar A={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},B={};function C(a,b,c){this.props=a;this.context=b;this.refs=B;this.updater=c||A}C.prototype.isReactComponent={};C.prototype.setState=function(a,b){if(\"object\"!==typeof a&&\"function\"!==typeof a&&null!=a)throw Error(z(85));this.updater.enqueueSetState(this,a,b,\"setState\")};C.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,\"forceUpdate\")};\nfunction D(){}D.prototype=C.prototype;function E(a,b,c){this.props=a;this.context=b;this.refs=B;this.updater=c||A}var F=E.prototype=new D;F.constructor=E;l(F,C.prototype);F.isPureReactComponent=!0;var G={current:null},H=Object.prototype.hasOwnProperty,I={key:!0,ref:!0,__self:!0,__source:!0};\nfunction J(a,b,c){var e,d={},k=null,h=null;if(null!=b)for(e in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=\"\"+b.key),b)H.call(b,e)&&!I.hasOwnProperty(e)&&(d[e]=b[e]);var g=arguments.length-2;if(1===g)d.children=c;else if(1<g){for(var f=Array(g),m=0;m<g;m++)f[m]=arguments[m+2];d.children=f}if(a&&a.defaultProps)for(e in g=a.defaultProps,g)void 0===d[e]&&(d[e]=g[e]);return{$$typeof:n,type:a,key:k,ref:h,props:d,_owner:G.current}}\nfunction K(a,b){return{$$typeof:n,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function L(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===n}function escape(a){var b={\"=\":\"=0\",\":\":\"=2\"};return\"$\"+a.replace(/[=:]/g,function(a){return b[a]})}var M=/\\/+/g;function N(a,b){return\"object\"===typeof a&&null!==a&&null!=a.key?escape(\"\"+a.key):b.toString(36)}\nfunction O(a,b,c,e,d){var k=typeof a;if(\"undefined\"===k||\"boolean\"===k)a=null;var h=!1;if(null===a)h=!0;else switch(k){case \"string\":case \"number\":h=!0;break;case \"object\":switch(a.$$typeof){case n:case p:h=!0}}if(h)return h=a,d=d(h),a=\"\"===e?\".\"+N(h,0):e,Array.isArray(d)?(c=\"\",null!=a&&(c=a.replace(M,\"$&/\")+\"/\"),O(d,b,c,\"\",function(a){return a})):null!=d&&(L(d)&&(d=K(d,c+(!d.key||h&&h.key===d.key?\"\":(\"\"+d.key).replace(M,\"$&/\")+\"/\")+a)),b.push(d)),1;h=0;e=\"\"===e?\".\":e+\":\";if(Array.isArray(a))for(var g=\n0;g<a.length;g++){k=a[g];var f=e+N(k,g);h+=O(k,b,c,f,d)}else if(f=y(a),\"function\"===typeof f)for(a=f.call(a),g=0;!(k=a.next()).done;)k=k.value,f=e+N(k,g++),h+=O(k,b,c,f,d);else if(\"object\"===k)throw b=\"\"+a,Error(z(31,\"[object Object]\"===b?\"object with keys {\"+Object.keys(a).join(\", \")+\"}\":b));return h}function P(a,b,c){if(null==a)return a;var e=[],d=0;O(a,e,\"\",\"\",function(a){return b.call(c,a,d++)});return e}\nfunction Q(a){if(-1===a._status){var b=a._result;b=b();a._status=0;a._result=b;b.then(function(b){0===a._status&&(b=b.default,a._status=1,a._result=b)},function(b){0===a._status&&(a._status=2,a._result=b)})}if(1===a._status)return a._result;throw a._result;}var R={current:null};function S(){var a=R.current;if(null===a)throw Error(z(321));return a}var T={ReactCurrentDispatcher:R,ReactCurrentBatchConfig:{transition:0},ReactCurrentOwner:G,IsSomeRendererActing:{current:!1},assign:l};\nexports.Children={map:P,forEach:function(a,b,c){P(a,function(){b.apply(this,arguments)},c)},count:function(a){var b=0;P(a,function(){b++});return b},toArray:function(a){return P(a,function(a){return a})||[]},only:function(a){if(!L(a))throw Error(z(143));return a}};exports.Component=C;exports.PureComponent=E;exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=T;\nexports.cloneElement=function(a,b,c){if(null===a||void 0===a)throw Error(z(267,a));var e=l({},a.props),d=a.key,k=a.ref,h=a._owner;if(null!=b){void 0!==b.ref&&(k=b.ref,h=G.current);void 0!==b.key&&(d=\"\"+b.key);if(a.type&&a.type.defaultProps)var g=a.type.defaultProps;for(f in b)H.call(b,f)&&!I.hasOwnProperty(f)&&(e[f]=void 0===b[f]&&void 0!==g?g[f]:b[f])}var f=arguments.length-2;if(1===f)e.children=c;else if(1<f){g=Array(f);for(var m=0;m<f;m++)g[m]=arguments[m+2];e.children=g}return{$$typeof:n,type:a.type,\nkey:d,ref:k,props:e,_owner:h}};exports.createContext=function(a,b){void 0===b&&(b=null);a={$$typeof:r,_calculateChangedBits:b,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null};a.Provider={$$typeof:q,_context:a};return a.Consumer=a};exports.createElement=J;exports.createFactory=function(a){var b=J.bind(null,a);b.type=a;return b};exports.createRef=function(){return{current:null}};exports.forwardRef=function(a){return{$$typeof:t,render:a}};exports.isValidElement=L;\nexports.lazy=function(a){return{$$typeof:v,_payload:{_status:-1,_result:a},_init:Q}};exports.memo=function(a,b){return{$$typeof:u,type:a,compare:void 0===b?null:b}};exports.useCallback=function(a,b){return S().useCallback(a,b)};exports.useContext=function(a,b){return S().useContext(a,b)};exports.useDebugValue=function(){};exports.useEffect=function(a,b){return S().useEffect(a,b)};exports.useImperativeHandle=function(a,b,c){return S().useImperativeHandle(a,b,c)};\nexports.useLayoutEffect=function(a,b){return S().useLayoutEffect(a,b)};exports.useMemo=function(a,b){return S().useMemo(a,b)};exports.useReducer=function(a,b,c){return S().useReducer(a,b,c)};exports.useRef=function(a){return S().useRef(a)};exports.useState=function(a){return S().useState(a)};exports.version=\"17.0.2\";\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react.production.min.js');\n} else {\n module.exports = require('./cjs/react.development.js');\n}\n","/**\n * This file automatically generated from `pre-publish.js`.\n * Do not manually edit.\n */\n\nmodule.exports = {\n \"area\": true,\n \"base\": true,\n \"br\": true,\n \"col\": true,\n \"embed\": true,\n \"hr\": true,\n \"img\": true,\n \"input\": true,\n \"link\": true,\n \"meta\": true,\n \"param\": true,\n \"source\": true,\n \"track\": true,\n \"wbr\": true\n};\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nvar __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nfunction __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nfunction __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nfunction __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\n\nexport { __assign, __read, __rest, __spreadArray, __values };\n","var ActionTypes;\n\n(function (ActionTypes) {\n ActionTypes[\"Start\"] = \"xstate.start\";\n ActionTypes[\"Stop\"] = \"xstate.stop\";\n ActionTypes[\"Raise\"] = \"xstate.raise\";\n ActionTypes[\"Send\"] = \"xstate.send\";\n ActionTypes[\"Cancel\"] = \"xstate.cancel\";\n ActionTypes[\"NullEvent\"] = \"\";\n ActionTypes[\"Assign\"] = \"xstate.assign\";\n ActionTypes[\"After\"] = \"xstate.after\";\n ActionTypes[\"DoneState\"] = \"done.state\";\n ActionTypes[\"DoneInvoke\"] = \"done.invoke\";\n ActionTypes[\"Log\"] = \"xstate.log\";\n ActionTypes[\"Init\"] = \"xstate.init\";\n ActionTypes[\"Invoke\"] = \"xstate.invoke\";\n ActionTypes[\"ErrorExecution\"] = \"error.execution\";\n ActionTypes[\"ErrorCommunication\"] = \"error.communication\";\n ActionTypes[\"ErrorPlatform\"] = \"error.platform\";\n ActionTypes[\"ErrorCustom\"] = \"xstate.error\";\n ActionTypes[\"Update\"] = \"xstate.update\";\n ActionTypes[\"Pure\"] = \"xstate.pure\";\n ActionTypes[\"Choose\"] = \"xstate.choose\";\n})(ActionTypes || (ActionTypes = {}));\n\nvar SpecialTargets;\n\n(function (SpecialTargets) {\n SpecialTargets[\"Parent\"] = \"#_parent\";\n SpecialTargets[\"Internal\"] = \"#_internal\";\n})(SpecialTargets || (SpecialTargets = {}));\n\nexport { ActionTypes, SpecialTargets };\n","import { ActionTypes } from './types.js';\n\nvar start = ActionTypes.Start;\nvar stop = ActionTypes.Stop;\nvar raise = ActionTypes.Raise;\nvar send = ActionTypes.Send;\nvar cancel = ActionTypes.Cancel;\nvar nullEvent = ActionTypes.NullEvent;\nvar assign = ActionTypes.Assign;\nvar after = ActionTypes.After;\nvar doneState = ActionTypes.DoneState;\nvar log = ActionTypes.Log;\nvar init = ActionTypes.Init;\nvar invoke = ActionTypes.Invoke;\nvar errorExecution = ActionTypes.ErrorExecution;\nvar errorPlatform = ActionTypes.ErrorPlatform;\nvar error = ActionTypes.ErrorCustom;\nvar update = ActionTypes.Update;\nvar choose = ActionTypes.Choose;\nvar pure = ActionTypes.Pure;\n\nexport { after, assign, cancel, choose, doneState, error, errorExecution, errorPlatform, init, invoke, log, nullEvent, pure, raise, send, start, stop, update };\n","import { __values, __spreadArray, __read, __assign } from './_virtual/_tslib.js';\nimport { SpecialTargets } from './types.js';\nimport { raise, send } from './actionTypes.js';\nimport { DEFAULT_GUARD_TYPE, TARGETLESS_KEY, STATE_DELIMITER } from './constants.js';\nimport { IS_PRODUCTION } from './environment.js';\n\nvar _a;\nfunction keys(value) {\n return Object.keys(value);\n}\nfunction matchesState(parentStateId, childStateId, delimiter) {\n if (delimiter === void 0) {\n delimiter = STATE_DELIMITER;\n }\n\n var parentStateValue = toStateValue(parentStateId, delimiter);\n var childStateValue = toStateValue(childStateId, delimiter);\n\n if (isString(childStateValue)) {\n if (isString(parentStateValue)) {\n return childStateValue === parentStateValue;\n } // Parent more specific than child\n\n\n return false;\n }\n\n if (isString(parentStateValue)) {\n return parentStateValue in childStateValue;\n }\n\n return Object.keys(parentStateValue).every(function (key) {\n if (!(key in childStateValue)) {\n return false;\n }\n\n return matchesState(parentStateValue[key], childStateValue[key]);\n });\n}\nfunction getEventType(event) {\n try {\n return isString(event) || typeof event === 'number' ? \"\".concat(event) : event.type;\n } catch (e) {\n throw new Error('Events must be strings or objects with a string event.type property.');\n }\n}\nfunction getActionType(action) {\n try {\n return isString(action) || typeof action === 'number' ? \"\".concat(action) : isFunction(action) ? action.name : action.type;\n } catch (e) {\n throw new Error('Actions must be strings or objects with a string action.type property.');\n }\n}\nfunction toStatePath(stateId, delimiter) {\n try {\n if (isArray(stateId)) {\n return stateId;\n }\n\n return stateId.toString().split(delimiter);\n } catch (e) {\n throw new Error(\"'\".concat(stateId, \"' is not a valid state path.\"));\n }\n}\nfunction isStateLike(state) {\n return typeof state === 'object' && 'value' in state && 'context' in state && 'event' in state && '_event' in state;\n}\nfunction toStateValue(stateValue, delimiter) {\n if (isStateLike(stateValue)) {\n return stateValue.value;\n }\n\n if (isArray(stateValue)) {\n return pathToStateValue(stateValue);\n }\n\n if (typeof stateValue !== 'string') {\n return stateValue;\n }\n\n var statePath = toStatePath(stateValue, delimiter);\n return pathToStateValue(statePath);\n}\nfunction pathToStateValue(statePath) {\n if (statePath.length === 1) {\n return statePath[0];\n }\n\n var value = {};\n var marker = value;\n\n for (var i = 0; i < statePath.length - 1; i++) {\n if (i === statePath.length - 2) {\n marker[statePath[i]] = statePath[i + 1];\n } else {\n marker[statePath[i]] = {};\n marker = marker[statePath[i]];\n }\n }\n\n return value;\n}\nfunction mapValues(collection, iteratee) {\n var result = {};\n var collectionKeys = Object.keys(collection);\n\n for (var i = 0; i < collectionKeys.length; i++) {\n var key = collectionKeys[i];\n result[key] = iteratee(collection[key], key, collection, i);\n }\n\n return result;\n}\nfunction mapFilterValues(collection, iteratee, predicate) {\n var e_1, _a;\n\n var result = {};\n\n try {\n for (var _b = __values(Object.keys(collection)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var key = _c.value;\n var item = collection[key];\n\n if (!predicate(item)) {\n continue;\n }\n\n result[key] = iteratee(item, key, collection);\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n\n return result;\n}\n/**\r\n * Retrieves a value at the given path.\r\n * @param props The deep path to the prop of the desired value\r\n */\n\nvar path = function (props) {\n return function (object) {\n var e_2, _a;\n\n var result = object;\n\n try {\n for (var props_1 = __values(props), props_1_1 = props_1.next(); !props_1_1.done; props_1_1 = props_1.next()) {\n var prop = props_1_1.value;\n result = result[prop];\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (props_1_1 && !props_1_1.done && (_a = props_1.return)) _a.call(props_1);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n\n return result;\n };\n};\n/**\r\n * Retrieves a value at the given path via the nested accessor prop.\r\n * @param props The deep path to the prop of the desired value\r\n */\n\nfunction nestedPath(props, accessorProp) {\n return function (object) {\n var e_3, _a;\n\n var result = object;\n\n try {\n for (var props_2 = __values(props), props_2_1 = props_2.next(); !props_2_1.done; props_2_1 = props_2.next()) {\n var prop = props_2_1.value;\n result = result[accessorProp][prop];\n }\n } catch (e_3_1) {\n e_3 = {\n error: e_3_1\n };\n } finally {\n try {\n if (props_2_1 && !props_2_1.done && (_a = props_2.return)) _a.call(props_2);\n } finally {\n if (e_3) throw e_3.error;\n }\n }\n\n return result;\n };\n}\nfunction toStatePaths(stateValue) {\n if (!stateValue) {\n return [[]];\n }\n\n if (isString(stateValue)) {\n return [[stateValue]];\n }\n\n var result = flatten(Object.keys(stateValue).map(function (key) {\n var subStateValue = stateValue[key];\n\n if (typeof subStateValue !== 'string' && (!subStateValue || !Object.keys(subStateValue).length)) {\n return [[key]];\n }\n\n return toStatePaths(stateValue[key]).map(function (subPath) {\n return [key].concat(subPath);\n });\n }));\n return result;\n}\nfunction pathsToStateValue(paths) {\n var e_4, _a;\n\n var result = {};\n\n if (paths && paths.length === 1 && paths[0].length === 1) {\n return paths[0][0];\n }\n\n try {\n for (var paths_1 = __values(paths), paths_1_1 = paths_1.next(); !paths_1_1.done; paths_1_1 = paths_1.next()) {\n var currentPath = paths_1_1.value;\n var marker = result; // tslint:disable-next-line:prefer-for-of\n\n for (var i = 0; i < currentPath.length; i++) {\n var subPath = currentPath[i];\n\n if (i === currentPath.length - 2) {\n marker[subPath] = currentPath[i + 1];\n break;\n }\n\n marker[subPath] = marker[subPath] || {};\n marker = marker[subPath];\n }\n }\n } catch (e_4_1) {\n e_4 = {\n error: e_4_1\n };\n } finally {\n try {\n if (paths_1_1 && !paths_1_1.done && (_a = paths_1.return)) _a.call(paths_1);\n } finally {\n if (e_4) throw e_4.error;\n }\n }\n\n return result;\n}\nfunction flatten(array) {\n var _a;\n\n return (_a = []).concat.apply(_a, __spreadArray([], __read(array), false));\n}\nfunction toArrayStrict(value) {\n if (isArray(value)) {\n return value;\n }\n\n return [value];\n}\nfunction toArray(value) {\n if (value === undefined) {\n return [];\n }\n\n return toArrayStrict(value);\n}\nfunction mapContext(mapper, context, _event) {\n var e_5, _a;\n\n if (isFunction(mapper)) {\n return mapper(context, _event.data);\n }\n\n var result = {};\n\n try {\n for (var _b = __values(Object.keys(mapper)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var key = _c.value;\n var subMapper = mapper[key];\n\n if (isFunction(subMapper)) {\n result[key] = subMapper(context, _event.data);\n } else {\n result[key] = subMapper;\n }\n }\n } catch (e_5_1) {\n e_5 = {\n error: e_5_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_5) throw e_5.error;\n }\n }\n\n return result;\n}\nfunction isBuiltInEvent(eventType) {\n return /^(done|error)\\./.test(eventType);\n}\nfunction isPromiseLike(value) {\n if (value instanceof Promise) {\n return true;\n } // Check if shape matches the Promise/A+ specification for a \"thenable\".\n\n\n if (value !== null && (isFunction(value) || typeof value === 'object') && isFunction(value.then)) {\n return true;\n }\n\n return false;\n}\nfunction isBehavior(value) {\n return value !== null && typeof value === 'object' && 'transition' in value && typeof value.transition === 'function';\n}\nfunction partition(items, predicate) {\n var e_6, _a;\n\n var _b = __read([[], []], 2),\n truthy = _b[0],\n falsy = _b[1];\n\n try {\n for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {\n var item = items_1_1.value;\n\n if (predicate(item)) {\n truthy.push(item);\n } else {\n falsy.push(item);\n }\n }\n } catch (e_6_1) {\n e_6 = {\n error: e_6_1\n };\n } finally {\n try {\n if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);\n } finally {\n if (e_6) throw e_6.error;\n }\n }\n\n return [truthy, falsy];\n}\nfunction updateHistoryStates(hist, stateValue) {\n return mapValues(hist.states, function (subHist, key) {\n if (!subHist) {\n return undefined;\n }\n\n var subStateValue = (isString(stateValue) ? undefined : stateValue[key]) || (subHist ? subHist.current : undefined);\n\n if (!subStateValue) {\n return undefined;\n }\n\n return {\n current: subStateValue,\n states: updateHistoryStates(subHist, subStateValue)\n };\n });\n}\nfunction updateHistoryValue(hist, stateValue) {\n return {\n current: stateValue,\n states: updateHistoryStates(hist, stateValue)\n };\n}\nfunction updateContext(context, _event, assignActions, state) {\n if (!IS_PRODUCTION) {\n warn(!!context, 'Attempting to update undefined context');\n }\n\n var updatedContext = context ? assignActions.reduce(function (acc, assignAction) {\n var e_7, _a;\n\n var assignment = assignAction.assignment;\n var meta = {\n state: state,\n action: assignAction,\n _event: _event\n };\n var partialUpdate = {};\n\n if (isFunction(assignment)) {\n partialUpdate = assignment(acc, _event.data, meta);\n } else {\n try {\n for (var _b = __values(Object.keys(assignment)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var key = _c.value;\n var propAssignment = assignment[key];\n partialUpdate[key] = isFunction(propAssignment) ? propAssignment(acc, _event.data, meta) : propAssignment;\n }\n } catch (e_7_1) {\n e_7 = {\n error: e_7_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_7) throw e_7.error;\n }\n }\n }\n\n return Object.assign({}, acc, partialUpdate);\n }, context) : context;\n return updatedContext;\n} // tslint:disable-next-line:no-empty\n\nvar warn = function () {};\n\nif (!IS_PRODUCTION) {\n warn = function (condition, message) {\n var error = condition instanceof Error ? condition : undefined;\n\n if (!error && condition) {\n return;\n }\n\n if (console !== undefined) {\n var args = [\"Warning: \".concat(message)];\n\n if (error) {\n args.push(error);\n } // tslint:disable-next-line:no-console\n\n\n console.warn.apply(console, args);\n }\n };\n}\nfunction isArray(value) {\n return Array.isArray(value);\n} // tslint:disable-next-line:ban-types\n\nfunction isFunction(value) {\n return typeof value === 'function';\n}\nfunction isString(value) {\n return typeof value === 'string';\n}\nfunction toGuard(condition, guardMap) {\n if (!condition) {\n return undefined;\n }\n\n if (isString(condition)) {\n return {\n type: DEFAULT_GUARD_TYPE,\n name: condition,\n predicate: guardMap ? guardMap[condition] : undefined\n };\n }\n\n if (isFunction(condition)) {\n return {\n type: DEFAULT_GUARD_TYPE,\n name: condition.name,\n predicate: condition\n };\n }\n\n return condition;\n}\nfunction isObservable(value) {\n try {\n return 'subscribe' in value && isFunction(value.subscribe);\n } catch (e) {\n return false;\n }\n}\nvar symbolObservable = /*#__PURE__*/function () {\n return typeof Symbol === 'function' && Symbol.observable || '@@observable';\n}(); // TODO: to be removed in v5, left it out just to minimize the scope of the change and maintain compatibility with older versions of integration paackages\n\nvar interopSymbols = (_a = {}, _a[symbolObservable] = function () {\n return this;\n}, _a[Symbol.observable] = function () {\n return this;\n}, _a);\nfunction isMachine(value) {\n return !!value && '__xstatenode' in value;\n}\nfunction isActor(value) {\n return !!value && typeof value.send === 'function';\n}\nvar uniqueId = /*#__PURE__*/function () {\n var currentId = 0;\n return function () {\n currentId++;\n return currentId.toString(16);\n };\n}();\nfunction toEventObject(event, payload // id?: TEvent['type']\n) {\n if (isString(event) || typeof event === 'number') {\n return __assign({\n type: event\n }, payload);\n }\n\n return event;\n}\nfunction toSCXMLEvent(event, scxmlEvent) {\n if (!isString(event) && '$$type' in event && event.$$type === 'scxml') {\n return event;\n }\n\n var eventObject = toEventObject(event);\n return __assign({\n name: eventObject.type,\n data: eventObject,\n $$type: 'scxml',\n type: 'external'\n }, scxmlEvent);\n}\nfunction toTransitionConfigArray(event, configLike) {\n var transitions = toArrayStrict(configLike).map(function (transitionLike) {\n if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string' || isMachine(transitionLike)) {\n return {\n target: transitionLike,\n event: event\n };\n }\n\n return __assign(__assign({}, transitionLike), {\n event: event\n });\n });\n return transitions;\n}\nfunction normalizeTarget(target) {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n\n return toArray(target);\n}\nfunction reportUnhandledExceptionOnInvocation(originalError, currentError, id) {\n if (!IS_PRODUCTION) {\n var originalStackTrace = originalError.stack ? \" Stacktrace was '\".concat(originalError.stack, \"'\") : '';\n\n if (originalError === currentError) {\n // tslint:disable-next-line:no-console\n console.error(\"Missing onError handler for invocation '\".concat(id, \"', error was '\").concat(originalError, \"'.\").concat(originalStackTrace));\n } else {\n var stackTrace = currentError.stack ? \" Stacktrace was '\".concat(currentError.stack, \"'\") : ''; // tslint:disable-next-line:no-console\n\n console.error(\"Missing onError handler and/or unhandled exception/promise rejection for invocation '\".concat(id, \"'. \") + \"Original error: '\".concat(originalError, \"'. \").concat(originalStackTrace, \" Current error is '\").concat(currentError, \"'.\").concat(stackTrace));\n }\n }\n}\nfunction evaluateGuard(machine, guard, context, _event, state) {\n var guards = machine.options.guards;\n var guardMeta = {\n state: state,\n cond: guard,\n _event: _event\n }; // TODO: do not hardcode!\n\n if (guard.type === DEFAULT_GUARD_TYPE) {\n return ((guards === null || guards === void 0 ? void 0 : guards[guard.name]) || guard.predicate)(context, _event.data, guardMeta);\n }\n\n var condFn = guards === null || guards === void 0 ? void 0 : guards[guard.type];\n\n if (!condFn) {\n throw new Error(\"Guard '\".concat(guard.type, \"' is not implemented on machine '\").concat(machine.id, \"'.\"));\n }\n\n return condFn(context, _event.data, guardMeta);\n}\nfunction toInvokeSource(src) {\n if (typeof src === 'string') {\n return {\n type: src\n };\n }\n\n return src;\n}\nfunction toObserver(nextHandler, errorHandler, completionHandler) {\n var noop = function () {};\n\n var isObserver = typeof nextHandler === 'object';\n var self = isObserver ? nextHandler : null;\n return {\n next: ((isObserver ? nextHandler.next : nextHandler) || noop).bind(self),\n error: ((isObserver ? nextHandler.error : errorHandler) || noop).bind(self),\n complete: ((isObserver ? nextHandler.complete : completionHandler) || noop).bind(self)\n };\n}\nfunction createInvokeId(stateNodeId, index) {\n return \"\".concat(stateNodeId, \":invocation[\").concat(index, \"]\");\n}\nfunction isRaisableAction(action) {\n return (action.type === raise || action.type === send && action.to === SpecialTargets.Internal) && typeof action.delay !== 'number';\n}\n\nexport { createInvokeId, evaluateGuard, flatten, getActionType, getEventType, interopSymbols, isActor, isArray, isBehavior, isBuiltInEvent, isFunction, isMachine, isObservable, isPromiseLike, isRaisableAction, isStateLike, isString, keys, mapContext, mapFilterValues, mapValues, matchesState, nestedPath, normalizeTarget, partition, path, pathToStateValue, pathsToStateValue, reportUnhandledExceptionOnInvocation, symbolObservable, toArray, toArrayStrict, toEventObject, toGuard, toInvokeSource, toObserver, toSCXMLEvent, toStatePath, toStatePaths, toStateValue, toTransitionConfigArray, uniqueId, updateContext, updateHistoryStates, updateHistoryValue, warn };\n","var STATE_DELIMITER = '.';\nvar EMPTY_ACTIVITY_MAP = {};\nvar DEFAULT_GUARD_TYPE = 'xstate.guard';\nvar TARGETLESS_KEY = '';\n\nexport { DEFAULT_GUARD_TYPE, EMPTY_ACTIVITY_MAP, STATE_DELIMITER, TARGETLESS_KEY };\n","var IS_PRODUCTION = process.env.NODE_ENV === 'production';\n\nexport { IS_PRODUCTION };\n","import { __assign, __spreadArray, __read, __values } from './_virtual/_tslib.js';\nimport { SpecialTargets, ActionTypes } from './types.js';\nimport { init, raise as raise$1, send as send$1, update, log as log$1, cancel as cancel$1, assign as assign$1, error as error$1, stop as stop$1, pure as pure$1, choose as choose$1 } from './actionTypes.js';\nimport * as actionTypes from './actionTypes.js';\nexport { actionTypes };\nimport { toSCXMLEvent, isString, isFunction, toEventObject, getEventType, updateContext, flatten, isArray, toArray, toGuard, evaluateGuard, warn } from './utils.js';\nimport { IS_PRODUCTION } from './environment.js';\n\nvar initEvent = /*#__PURE__*/toSCXMLEvent({\n type: init\n});\nfunction getActionFunction(actionType, actionFunctionMap) {\n return actionFunctionMap ? actionFunctionMap[actionType] || undefined : undefined;\n}\nfunction toActionObject(action, actionFunctionMap) {\n var actionObject;\n\n if (isString(action) || typeof action === 'number') {\n var exec = getActionFunction(action, actionFunctionMap);\n\n if (isFunction(exec)) {\n actionObject = {\n type: action,\n exec: exec\n };\n } else if (exec) {\n actionObject = exec;\n } else {\n actionObject = {\n type: action,\n exec: undefined\n };\n }\n } else if (isFunction(action)) {\n actionObject = {\n // Convert action to string if unnamed\n type: action.name || action.toString(),\n exec: action\n };\n } else {\n var exec = getActionFunction(action.type, actionFunctionMap);\n\n if (isFunction(exec)) {\n actionObject = __assign(__assign({}, action), {\n exec: exec\n });\n } else if (exec) {\n var actionType = exec.type || action.type;\n actionObject = __assign(__assign(__assign({}, exec), action), {\n type: actionType\n });\n } else {\n actionObject = action;\n }\n }\n\n return actionObject;\n}\nvar toActionObjects = function (action, actionFunctionMap) {\n if (!action) {\n return [];\n }\n\n var actions = isArray(action) ? action : [action];\n return actions.map(function (subAction) {\n return toActionObject(subAction, actionFunctionMap);\n });\n};\nfunction toActivityDefinition(action) {\n var actionObject = toActionObject(action);\n return __assign(__assign({\n id: isString(action) ? action : actionObject.id\n }, actionObject), {\n type: actionObject.type\n });\n}\n/**\r\n * Raises an event. This places the event in the internal event queue, so that\r\n * the event is immediately consumed by the machine in the current step.\r\n *\r\n * @param eventType The event to raise.\r\n */\n\nfunction raise(event, options) {\n return {\n type: raise$1,\n event: typeof event === 'function' ? event : toEventObject(event),\n delay: options ? options.delay : undefined,\n id: options === null || options === void 0 ? void 0 : options.id\n };\n}\nfunction resolveRaise(action, ctx, _event, delaysMap) {\n var meta = {\n _event: _event\n };\n var resolvedEvent = toSCXMLEvent(isFunction(action.event) ? action.event(ctx, _event.data, meta) : action.event);\n var resolvedDelay;\n\n if (isString(action.delay)) {\n var configDelay = delaysMap && delaysMap[action.delay];\n resolvedDelay = isFunction(configDelay) ? configDelay(ctx, _event.data, meta) : configDelay;\n } else {\n resolvedDelay = isFunction(action.delay) ? action.delay(ctx, _event.data, meta) : action.delay;\n }\n\n return __assign(__assign({}, action), {\n type: raise$1,\n _event: resolvedEvent,\n delay: resolvedDelay\n });\n}\n/**\r\n * Sends an event. This returns an action that will be read by an interpreter to\r\n * send the event in the next step, after the current step is finished executing.\r\n *\r\n * @deprecated Use the `sendTo(...)` action creator instead.\r\n *\r\n * @param event The event to send.\r\n * @param options Options to pass into the send event:\r\n * - `id` - The unique send event identifier (used with `cancel()`).\r\n * - `delay` - The number of milliseconds to delay the sending of the event.\r\n * - `to` - The target of this event (by default, the machine the event was sent from).\r\n */\n\nfunction send(event, options) {\n return {\n to: options ? options.to : undefined,\n type: send$1,\n event: isFunction(event) ? event : toEventObject(event),\n delay: options ? options.delay : undefined,\n // TODO: don't auto-generate IDs here like that\n // there is too big chance of the ID collision\n id: options && options.id !== undefined ? options.id : isFunction(event) ? event.name : getEventType(event)\n };\n}\nfunction resolveSend(action, ctx, _event, delaysMap) {\n var meta = {\n _event: _event\n }; // TODO: helper function for resolving Expr\n\n var resolvedEvent = toSCXMLEvent(isFunction(action.event) ? action.event(ctx, _event.data, meta) : action.event);\n var resolvedDelay;\n\n if (isString(action.delay)) {\n var configDelay = delaysMap && delaysMap[action.delay];\n resolvedDelay = isFunction(configDelay) ? configDelay(ctx, _event.data, meta) : configDelay;\n } else {\n resolvedDelay = isFunction(action.delay) ? action.delay(ctx, _event.data, meta) : action.delay;\n }\n\n var resolvedTarget = isFunction(action.to) ? action.to(ctx, _event.data, meta) : action.to;\n return __assign(__assign({}, action), {\n to: resolvedTarget,\n _event: resolvedEvent,\n event: resolvedEvent.data,\n delay: resolvedDelay\n });\n}\n/**\r\n * Sends an event to this machine's parent.\r\n *\r\n * @param event The event to send to the parent machine.\r\n * @param options Options to pass into the send event.\r\n */\n\nfunction sendParent(event, options) {\n return send(event, __assign(__assign({}, options), {\n to: SpecialTargets.Parent\n }));\n}\n/**\r\n * Sends an event to an actor.\r\n *\r\n * @param actor The `ActorRef` to send the event to.\r\n * @param event The event to send, or an expression that evaluates to the event to send\r\n * @param options Send action options\r\n * @returns An XState send action object\r\n */\n\nfunction sendTo(actor, event, options) {\n return send(event, __assign(__assign({}, options), {\n to: actor\n }));\n}\n/**\r\n * Sends an update event to this machine's parent.\r\n */\n\nfunction sendUpdate() {\n return sendParent(update);\n}\n/**\r\n * Sends an event back to the sender of the original event.\r\n *\r\n * @param event The event to send back to the sender\r\n * @param options Options to pass into the send event\r\n */\n\nfunction respond(event, options) {\n return send(event, __assign(__assign({}, options), {\n to: function (_, __, _a) {\n var _event = _a._event;\n return _event.origin; // TODO: handle when _event.origin is undefined\n }\n }));\n}\n\nvar defaultLogExpr = function (context, event) {\n return {\n context: context,\n event: event\n };\n};\n/**\r\n *\r\n * @param expr The expression function to evaluate which will be logged.\r\n * Takes in 2 arguments:\r\n * - `ctx` - the current state context\r\n * - `event` - the event that caused this action to be executed.\r\n * @param label The label to give to the logged expression.\r\n */\n\n\nfunction log(expr, label) {\n if (expr === void 0) {\n expr = defaultLogExpr;\n }\n\n return {\n type: log$1,\n label: label,\n expr: expr\n };\n}\nvar resolveLog = function (action, ctx, _event) {\n return __assign(__assign({}, action), {\n value: isString(action.expr) ? action.expr : action.expr(ctx, _event.data, {\n _event: _event\n })\n });\n};\n/**\r\n * Cancels an in-flight `send(...)` action. A canceled sent action will not\r\n * be executed, nor will its event be sent, unless it has already been sent\r\n * (e.g., if `cancel(...)` is called after the `send(...)` action's `delay`).\r\n *\r\n * @param sendId The `id` of the `send(...)` action to cancel.\r\n */\n\nvar cancel = function (sendId) {\n return {\n type: cancel$1,\n sendId: sendId\n };\n};\n/**\r\n * Starts an activity.\r\n *\r\n * @param activity The activity to start.\r\n */\n\nfunction start(activity) {\n var activityDef = toActivityDefinition(activity);\n return {\n type: ActionTypes.Start,\n activity: activityDef,\n exec: undefined\n };\n}\n/**\r\n * Stops an activity.\r\n *\r\n * @param actorRef The activity to stop.\r\n */\n\nfunction stop(actorRef) {\n var activity = isFunction(actorRef) ? actorRef : toActivityDefinition(actorRef);\n return {\n type: ActionTypes.Stop,\n activity: activity,\n exec: undefined\n };\n}\nfunction resolveStop(action, context, _event) {\n var actorRefOrString = isFunction(action.activity) ? action.activity(context, _event.data) : action.activity;\n var resolvedActorRef = typeof actorRefOrString === 'string' ? {\n id: actorRefOrString\n } : actorRefOrString;\n var actionObject = {\n type: ActionTypes.Stop,\n activity: resolvedActorRef\n };\n return actionObject;\n}\n/**\r\n * Updates the current context of the machine.\r\n *\r\n * @param assignment An object that represents the partial context to update.\r\n */\n\nvar assign = function (assignment) {\n return {\n type: assign$1,\n assignment: assignment\n };\n};\nfunction isActionObject(action) {\n return typeof action === 'object' && 'type' in action;\n}\n/**\r\n * Returns an event type that represents an implicit event that\r\n * is sent after the specified `delay`.\r\n *\r\n * @param delayRef The delay in milliseconds\r\n * @param id The state node ID where this event is handled\r\n */\n\nfunction after(delayRef, id) {\n var idSuffix = id ? \"#\".concat(id) : '';\n return \"\".concat(ActionTypes.After, \"(\").concat(delayRef, \")\").concat(idSuffix);\n}\n/**\r\n * Returns an event that represents that a final state node\r\n * has been reached in the parent state node.\r\n *\r\n * @param id The final state node's parent state node `id`\r\n * @param data The data to pass into the event\r\n */\n\nfunction done(id, data) {\n var type = \"\".concat(ActionTypes.DoneState, \".\").concat(id);\n var eventObject = {\n type: type,\n data: data\n };\n\n eventObject.toString = function () {\n return type;\n };\n\n return eventObject;\n}\n/**\r\n * Returns an event that represents that an invoked service has terminated.\r\n *\r\n * An invoked service is terminated when it has reached a top-level final state node,\r\n * but not when it is canceled.\r\n *\r\n * @param id The final state node ID\r\n * @param data The data to pass into the event\r\n */\n\nfunction doneInvoke(id, data) {\n var type = \"\".concat(ActionTypes.DoneInvoke, \".\").concat(id);\n var eventObject = {\n type: type,\n data: data\n };\n\n eventObject.toString = function () {\n return type;\n };\n\n return eventObject;\n}\nfunction error(id, data) {\n var type = \"\".concat(ActionTypes.ErrorPlatform, \".\").concat(id);\n var eventObject = {\n type: type,\n data: data\n };\n\n eventObject.toString = function () {\n return type;\n };\n\n return eventObject;\n}\nfunction pure(getActions) {\n return {\n type: ActionTypes.Pure,\n get: getActions\n };\n}\n/**\r\n * Forwards (sends) an event to a specified service.\r\n *\r\n * @param target The target service to forward the event to.\r\n * @param options Options to pass into the send action creator.\r\n */\n\nfunction forwardTo(target, options) {\n if (!IS_PRODUCTION && (!target || typeof target === 'function')) {\n var originalTarget_1 = target;\n\n target = function () {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n var resolvedTarget = typeof originalTarget_1 === 'function' ? originalTarget_1.apply(void 0, __spreadArray([], __read(args), false)) : originalTarget_1;\n\n if (!resolvedTarget) {\n throw new Error(\"Attempted to forward event to undefined actor. This risks an infinite loop in the sender.\");\n }\n\n return resolvedTarget;\n };\n }\n\n return send(function (_, event) {\n return event;\n }, __assign(__assign({}, options), {\n to: target\n }));\n}\n/**\r\n * Escalates an error by sending it as an event to this machine's parent.\r\n *\r\n * @param errorData The error data to send, or the expression function that\r\n * takes in the `context`, `event`, and `meta`, and returns the error data to send.\r\n * @param options Options to pass into the send action creator.\r\n */\n\nfunction escalate(errorData, options) {\n return sendParent(function (context, event, meta) {\n return {\n type: error$1,\n data: isFunction(errorData) ? errorData(context, event, meta) : errorData\n };\n }, __assign(__assign({}, options), {\n to: SpecialTargets.Parent\n }));\n}\nfunction choose(conds) {\n return {\n type: ActionTypes.Choose,\n conds: conds\n };\n}\n\nvar pluckAssigns = function (actionBlocks) {\n var e_1, _a;\n\n var assignActions = [];\n\n try {\n for (var actionBlocks_1 = __values(actionBlocks), actionBlocks_1_1 = actionBlocks_1.next(); !actionBlocks_1_1.done; actionBlocks_1_1 = actionBlocks_1.next()) {\n var block = actionBlocks_1_1.value;\n var i = 0;\n\n while (i < block.actions.length) {\n if (block.actions[i].type === assign$1) {\n assignActions.push(block.actions[i]);\n block.actions.splice(i, 1);\n continue;\n }\n\n i++;\n }\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (actionBlocks_1_1 && !actionBlocks_1_1.done && (_a = actionBlocks_1.return)) _a.call(actionBlocks_1);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n\n return assignActions;\n};\n\nfunction resolveActions(machine, currentState, currentContext, _event, actionBlocks, predictableExec, preserveActionOrder) {\n if (preserveActionOrder === void 0) {\n preserveActionOrder = false;\n }\n\n var assignActions = preserveActionOrder ? [] : pluckAssigns(actionBlocks);\n var updatedContext = assignActions.length ? updateContext(currentContext, _event, assignActions, currentState) : currentContext;\n var preservedContexts = preserveActionOrder ? [currentContext] : undefined;\n var deferredToBlockEnd = [];\n\n function handleAction(blockType, actionObject) {\n var _a;\n\n switch (actionObject.type) {\n case raise$1:\n {\n var raisedAction = resolveRaise(actionObject, updatedContext, _event, machine.options.delays);\n\n if (predictableExec && typeof raisedAction.delay === 'number') {\n predictableExec(raisedAction, updatedContext, _event);\n }\n\n return raisedAction;\n }\n\n case send$1:\n var sendAction = resolveSend(actionObject, updatedContext, _event, machine.options.delays); // TODO: fix ActionTypes.Init\n\n if (!IS_PRODUCTION) {\n var configuredDelay = actionObject.delay; // warn after resolving as we can create better contextual message here\n\n warn(!isString(configuredDelay) || typeof sendAction.delay === 'number', // tslint:disable-next-line:max-line-length\n \"No delay reference for delay expression '\".concat(configuredDelay, \"' was found on machine '\").concat(machine.id, \"'\"));\n }\n\n if (predictableExec && sendAction.to !== SpecialTargets.Internal) {\n if (blockType === 'entry') {\n deferredToBlockEnd.push(sendAction);\n } else {\n predictableExec(sendAction, updatedContext, _event);\n }\n }\n\n return sendAction;\n\n case log$1:\n {\n var resolved = resolveLog(actionObject, updatedContext, _event);\n predictableExec === null || predictableExec === void 0 ? void 0 : predictableExec(resolved, updatedContext, _event);\n return resolved;\n }\n\n case choose$1:\n {\n var chooseAction = actionObject;\n var matchedActions = (_a = chooseAction.conds.find(function (condition) {\n var guard = toGuard(condition.cond, machine.options.guards);\n return !guard || evaluateGuard(machine, guard, updatedContext, _event, !predictableExec ? currentState : undefined);\n })) === null || _a === void 0 ? void 0 : _a.actions;\n\n if (!matchedActions) {\n return [];\n }\n\n var _b = __read(resolveActions(machine, currentState, updatedContext, _event, [{\n type: blockType,\n actions: toActionObjects(toArray(matchedActions), machine.options.actions)\n }], predictableExec, preserveActionOrder), 2),\n resolvedActionsFromChoose = _b[0],\n resolvedContextFromChoose = _b[1];\n\n updatedContext = resolvedContextFromChoose;\n preservedContexts === null || preservedContexts === void 0 ? void 0 : preservedContexts.push(updatedContext);\n return resolvedActionsFromChoose;\n }\n\n case pure$1:\n {\n var matchedActions = actionObject.get(updatedContext, _event.data);\n\n if (!matchedActions) {\n return [];\n }\n\n var _c = __read(resolveActions(machine, currentState, updatedContext, _event, [{\n type: blockType,\n actions: toActionObjects(toArray(matchedActions), machine.options.actions)\n }], predictableExec, preserveActionOrder), 2),\n resolvedActionsFromPure = _c[0],\n resolvedContext = _c[1];\n\n updatedContext = resolvedContext;\n preservedContexts === null || preservedContexts === void 0 ? void 0 : preservedContexts.push(updatedContext);\n return resolvedActionsFromPure;\n }\n\n case stop$1:\n {\n var resolved = resolveStop(actionObject, updatedContext, _event);\n predictableExec === null || predictableExec === void 0 ? void 0 : predictableExec(resolved, currentContext, _event);\n return resolved;\n }\n\n case assign$1:\n {\n updatedContext = updateContext(updatedContext, _event, [actionObject], !predictableExec ? currentState : undefined);\n preservedContexts === null || preservedContexts === void 0 ? void 0 : preservedContexts.push(updatedContext);\n break;\n }\n\n default:\n var resolvedActionObject = toActionObject(actionObject, machine.options.actions);\n var exec_1 = resolvedActionObject.exec;\n\n if (predictableExec) {\n predictableExec(resolvedActionObject, updatedContext, _event);\n } else if (exec_1 && preservedContexts) {\n var contextIndex_1 = preservedContexts.length - 1;\n\n var wrapped = __assign(__assign({}, resolvedActionObject), {\n exec: function (_ctx) {\n var args = [];\n\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n\n exec_1.apply(void 0, __spreadArray([preservedContexts[contextIndex_1]], __read(args), false));\n }\n });\n\n resolvedActionObject = wrapped;\n }\n\n return resolvedActionObject;\n }\n }\n\n function processBlock(block) {\n var e_2, _a;\n\n var resolvedActions = [];\n\n try {\n for (var _b = __values(block.actions), _c = _b.next(); !_c.done; _c = _b.next()) {\n var action = _c.value;\n var resolved = handleAction(block.type, action);\n\n if (resolved) {\n resolvedActions = resolvedActions.concat(resolved);\n }\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n\n deferredToBlockEnd.forEach(function (action) {\n predictableExec(action, updatedContext, _event);\n });\n deferredToBlockEnd.length = 0;\n return resolvedActions;\n }\n\n var resolvedActions = flatten(actionBlocks.map(processBlock));\n return [resolvedActions, updatedContext];\n}\n\nexport { after, assign, cancel, choose, done, doneInvoke, error, escalate, forwardTo, getActionFunction, initEvent, isActionObject, log, pure, raise, resolveActions, resolveLog, resolveRaise, resolveSend, resolveStop, respond, send, sendParent, sendTo, sendUpdate, start, stop, toActionObject, toActionObjects, toActivityDefinition };\n","/**\r\n * Maintains a stack of the current service in scope.\r\n * This is used to provide the correct service to spawn().\r\n */\nvar serviceStack = [];\nvar provide = function (service, fn) {\n serviceStack.push(service);\n var result = fn(service);\n serviceStack.pop();\n return result;\n};\nvar consume = function (fn) {\n return fn(serviceStack[serviceStack.length - 1]);\n};\n\nexport { consume, provide };\n","import { __assign } from './_virtual/_tslib.js';\nimport { symbolObservable, toInvokeSource, mapContext, isMachine } from './utils.js';\nimport { provide } from './serviceScope.js';\n\nfunction createNullActor(id) {\n var _a;\n\n return _a = {\n id: id,\n send: function () {\n return void 0;\n },\n subscribe: function () {\n return {\n unsubscribe: function () {\n return void 0;\n }\n };\n },\n getSnapshot: function () {\n return undefined;\n },\n toJSON: function () {\n return {\n id: id\n };\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a;\n}\n/**\r\n * Creates a deferred actor that is able to be invoked given the provided\r\n * invocation information in its `.meta` value.\r\n *\r\n * @param invokeDefinition The meta information needed to invoke the actor.\r\n */\n\nfunction createInvocableActor(invokeDefinition, machine, context, _event) {\n var _a;\n\n var invokeSrc = toInvokeSource(invokeDefinition.src);\n var serviceCreator = (_a = machine === null || machine === void 0 ? void 0 : machine.options.services) === null || _a === void 0 ? void 0 : _a[invokeSrc.type];\n var resolvedData = invokeDefinition.data ? mapContext(invokeDefinition.data, context, _event) : undefined;\n var tempActor = serviceCreator ? createDeferredActor(serviceCreator, invokeDefinition.id, resolvedData) : createNullActor(invokeDefinition.id); // @ts-ignore\n\n tempActor.meta = invokeDefinition;\n return tempActor;\n}\nfunction createDeferredActor(entity, id, data) {\n var tempActor = createNullActor(id); // @ts-ignore\n\n tempActor.deferred = true;\n\n if (isMachine(entity)) {\n // \"mute\" the existing service scope so potential spawned actors within the `.initialState` stay deferred here\n var initialState_1 = tempActor.state = provide(undefined, function () {\n return (data ? entity.withContext(data) : entity).initialState;\n });\n\n tempActor.getSnapshot = function () {\n return initialState_1;\n };\n }\n\n return tempActor;\n}\nfunction isActor(item) {\n try {\n return typeof item.send === 'function';\n } catch (e) {\n return false;\n }\n}\nfunction isSpawnedActor(item) {\n return isActor(item) && 'id' in item;\n} // TODO: refactor the return type, this could be written in a better way but it's best to avoid unneccessary breaking changes now\n\nfunction toActorRef(actorRefLike) {\n var _a;\n\n return __assign((_a = {\n subscribe: function () {\n return {\n unsubscribe: function () {\n return void 0;\n }\n };\n },\n id: 'anonymous',\n getSnapshot: function () {\n return undefined;\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a), actorRefLike);\n}\n\nexport { createDeferredActor, createInvocableActor, createNullActor, isActor, isSpawnedActor, toActorRef };\n","import { __values, __spreadArray, __read } from './_virtual/_tslib.js';\nimport { flatten } from './utils.js';\n\nvar isLeafNode = function (stateNode) {\n return stateNode.type === 'atomic' || stateNode.type === 'final';\n};\nfunction getAllChildren(stateNode) {\n return Object.keys(stateNode.states).map(function (key) {\n return stateNode.states[key];\n });\n}\nfunction getChildren(stateNode) {\n return getAllChildren(stateNode).filter(function (sn) {\n return sn.type !== 'history';\n });\n}\nfunction getAllStateNodes(stateNode) {\n var stateNodes = [stateNode];\n\n if (isLeafNode(stateNode)) {\n return stateNodes;\n }\n\n return stateNodes.concat(flatten(getChildren(stateNode).map(getAllStateNodes)));\n}\nfunction getConfiguration(prevStateNodes, stateNodes) {\n var e_1, _a, e_2, _b, e_3, _c, e_4, _d;\n\n var prevConfiguration = new Set(prevStateNodes);\n var prevAdjList = getAdjList(prevConfiguration);\n var configuration = new Set(stateNodes);\n\n try {\n // add all ancestors\n for (var configuration_1 = __values(configuration), configuration_1_1 = configuration_1.next(); !configuration_1_1.done; configuration_1_1 = configuration_1.next()) {\n var s = configuration_1_1.value;\n var m = s.parent;\n\n while (m && !configuration.has(m)) {\n configuration.add(m);\n m = m.parent;\n }\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (configuration_1_1 && !configuration_1_1.done && (_a = configuration_1.return)) _a.call(configuration_1);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n\n var adjList = getAdjList(configuration);\n\n try {\n // add descendants\n for (var configuration_2 = __values(configuration), configuration_2_1 = configuration_2.next(); !configuration_2_1.done; configuration_2_1 = configuration_2.next()) {\n var s = configuration_2_1.value; // if previously active, add existing child nodes\n\n if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {\n if (prevAdjList.get(s)) {\n prevAdjList.get(s).forEach(function (sn) {\n return configuration.add(sn);\n });\n } else {\n s.initialStateNodes.forEach(function (sn) {\n return configuration.add(sn);\n });\n }\n } else {\n if (s.type === 'parallel') {\n try {\n for (var _e = (e_3 = void 0, __values(getChildren(s))), _f = _e.next(); !_f.done; _f = _e.next()) {\n var child = _f.value;\n\n if (!configuration.has(child)) {\n configuration.add(child);\n\n if (prevAdjList.get(child)) {\n prevAdjList.get(child).forEach(function (sn) {\n return configuration.add(sn);\n });\n } else {\n child.initialStateNodes.forEach(function (sn) {\n return configuration.add(sn);\n });\n }\n }\n }\n } catch (e_3_1) {\n e_3 = {\n error: e_3_1\n };\n } finally {\n try {\n if (_f && !_f.done && (_c = _e.return)) _c.call(_e);\n } finally {\n if (e_3) throw e_3.error;\n }\n }\n }\n }\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (configuration_2_1 && !configuration_2_1.done && (_b = configuration_2.return)) _b.call(configuration_2);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n\n try {\n // add all ancestors\n for (var configuration_3 = __values(configuration), configuration_3_1 = configuration_3.next(); !configuration_3_1.done; configuration_3_1 = configuration_3.next()) {\n var s = configuration_3_1.value;\n var m = s.parent;\n\n while (m && !configuration.has(m)) {\n configuration.add(m);\n m = m.parent;\n }\n }\n } catch (e_4_1) {\n e_4 = {\n error: e_4_1\n };\n } finally {\n try {\n if (configuration_3_1 && !configuration_3_1.done && (_d = configuration_3.return)) _d.call(configuration_3);\n } finally {\n if (e_4) throw e_4.error;\n }\n }\n\n return configuration;\n}\n\nfunction getValueFromAdj(baseNode, adjList) {\n var childStateNodes = adjList.get(baseNode);\n\n if (!childStateNodes) {\n return {}; // todo: fix?\n }\n\n if (baseNode.type === 'compound') {\n var childStateNode = childStateNodes[0];\n\n if (childStateNode) {\n if (isLeafNode(childStateNode)) {\n return childStateNode.key;\n }\n } else {\n return {};\n }\n }\n\n var stateValue = {};\n childStateNodes.forEach(function (csn) {\n stateValue[csn.key] = getValueFromAdj(csn, adjList);\n });\n return stateValue;\n}\n\nfunction getAdjList(configuration) {\n var e_5, _a;\n\n var adjList = new Map();\n\n try {\n for (var configuration_4 = __values(configuration), configuration_4_1 = configuration_4.next(); !configuration_4_1.done; configuration_4_1 = configuration_4.next()) {\n var s = configuration_4_1.value;\n\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n\n if (s.parent) {\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n\n adjList.get(s.parent).push(s);\n }\n }\n } catch (e_5_1) {\n e_5 = {\n error: e_5_1\n };\n } finally {\n try {\n if (configuration_4_1 && !configuration_4_1.done && (_a = configuration_4.return)) _a.call(configuration_4);\n } finally {\n if (e_5) throw e_5.error;\n }\n }\n\n return adjList;\n}\nfunction getValue(rootNode, configuration) {\n var config = getConfiguration([rootNode], configuration);\n return getValueFromAdj(rootNode, getAdjList(config));\n}\nfunction has(iterable, item) {\n if (Array.isArray(iterable)) {\n return iterable.some(function (member) {\n return member === item;\n });\n }\n\n if (iterable instanceof Set) {\n return iterable.has(item);\n }\n\n return false; // TODO: fix\n}\nfunction nextEvents(configuration) {\n return __spreadArray([], __read(new Set(flatten(__spreadArray([], __read(configuration.map(function (sn) {\n return sn.ownEvents;\n })), false)))), false);\n}\nfunction isInFinalState(configuration, stateNode) {\n if (stateNode.type === 'compound') {\n return getChildren(stateNode).some(function (s) {\n return s.type === 'final' && has(configuration, s);\n });\n }\n\n if (stateNode.type === 'parallel') {\n return getChildren(stateNode).every(function (sn) {\n return isInFinalState(configuration, sn);\n });\n }\n\n return false;\n}\nfunction getMeta(configuration) {\n if (configuration === void 0) {\n configuration = [];\n }\n\n return configuration.reduce(function (acc, stateNode) {\n if (stateNode.meta !== undefined) {\n acc[stateNode.id] = stateNode.meta;\n }\n\n return acc;\n }, {});\n}\nfunction getTagsFromConfiguration(configuration) {\n return new Set(flatten(configuration.map(function (sn) {\n return sn.tags;\n })));\n}\n\nexport { getAdjList, getAllChildren, getAllStateNodes, getChildren, getConfiguration, getMeta, getTagsFromConfiguration, getValue, has, isInFinalState, isLeafNode, nextEvents };\n","import { __assign, __spreadArray, __read, __rest } from './_virtual/_tslib.js';\nimport { EMPTY_ACTIVITY_MAP } from './constants.js';\nimport { isString, matchesState, warn } from './utils.js';\nimport { getMeta, nextEvents } from './stateUtils.js';\nimport { initEvent } from './actions.js';\nimport { IS_PRODUCTION } from './environment.js';\n\nfunction stateValuesEqual(a, b) {\n if (a === b) {\n return true;\n }\n\n if (a === undefined || b === undefined) {\n return false;\n }\n\n if (isString(a) || isString(b)) {\n return a === b;\n }\n\n var aKeys = Object.keys(a);\n var bKeys = Object.keys(b);\n return aKeys.length === bKeys.length && aKeys.every(function (key) {\n return stateValuesEqual(a[key], b[key]);\n });\n}\nfunction isStateConfig(state) {\n if (typeof state !== 'object' || state === null) {\n return false;\n }\n\n return 'value' in state && '_event' in state;\n}\n/**\r\n * @deprecated Use `isStateConfig(object)` or `state instanceof State` instead.\r\n */\n\nvar isState = isStateConfig;\nfunction bindActionToState(action, state) {\n var exec = action.exec;\n\n var boundAction = __assign(__assign({}, action), {\n exec: exec !== undefined ? function () {\n return exec(state.context, state.event, {\n action: action,\n state: state,\n _event: state._event\n });\n } : undefined\n });\n\n return boundAction;\n}\n\nvar State =\n/*#__PURE__*/\n\n/** @class */\nfunction () {\n /**\r\n * Creates a new State instance.\r\n * @param value The state value\r\n * @param context The extended state\r\n * @param historyValue The tree representing historical values of the state nodes\r\n * @param history The previous state\r\n * @param actions An array of action objects to execute as side-effects\r\n * @param activities A mapping of activities and whether they are started (`true`) or stopped (`false`).\r\n * @param meta\r\n * @param events Internal event queue. Should be empty with run-to-completion semantics.\r\n * @param configuration\r\n */\n function State(config) {\n var _this = this;\n\n var _a;\n\n this.actions = [];\n this.activities = EMPTY_ACTIVITY_MAP;\n this.meta = {};\n this.events = [];\n this.value = config.value;\n this.context = config.context;\n this._event = config._event;\n this._sessionid = config._sessionid;\n this.event = this._event.data;\n this.historyValue = config.historyValue;\n this.history = config.history;\n this.actions = config.actions || [];\n this.activities = config.activities || EMPTY_ACTIVITY_MAP;\n this.meta = getMeta(config.configuration);\n this.events = config.events || [];\n this.matches = this.matches.bind(this);\n this.toStrings = this.toStrings.bind(this);\n this.configuration = config.configuration;\n this.transitions = config.transitions;\n this.children = config.children;\n this.done = !!config.done;\n this.tags = (_a = Array.isArray(config.tags) ? new Set(config.tags) : config.tags) !== null && _a !== void 0 ? _a : new Set();\n this.machine = config.machine;\n Object.defineProperty(this, 'nextEvents', {\n get: function () {\n return nextEvents(_this.configuration);\n }\n });\n }\n /**\r\n * Creates a new State instance for the given `stateValue` and `context`.\r\n * @param stateValue\r\n * @param context\r\n */\n\n\n State.from = function (stateValue, context) {\n if (stateValue instanceof State) {\n if (stateValue.context !== context) {\n return new State({\n value: stateValue.value,\n context: context,\n _event: stateValue._event,\n _sessionid: null,\n historyValue: stateValue.historyValue,\n history: stateValue.history,\n actions: [],\n activities: stateValue.activities,\n meta: {},\n events: [],\n configuration: [],\n transitions: [],\n children: {}\n });\n }\n\n return stateValue;\n }\n\n var _event = initEvent;\n return new State({\n value: stateValue,\n context: context,\n _event: _event,\n _sessionid: null,\n historyValue: undefined,\n history: undefined,\n actions: [],\n activities: undefined,\n meta: undefined,\n events: [],\n configuration: [],\n transitions: [],\n children: {}\n });\n };\n /**\r\n * Creates a new State instance for the given `config`.\r\n * @param config The state config\r\n */\n\n\n State.create = function (config) {\n return new State(config);\n };\n /**\r\n * Creates a new `State` instance for the given `stateValue` and `context` with no actions (side-effects).\r\n * @param stateValue\r\n * @param context\r\n */\n\n\n State.inert = function (stateValue, context) {\n if (stateValue instanceof State) {\n if (!stateValue.actions.length) {\n return stateValue;\n }\n\n var _event = initEvent;\n return new State({\n value: stateValue.value,\n context: context,\n _event: _event,\n _sessionid: null,\n historyValue: stateValue.historyValue,\n history: stateValue.history,\n activities: stateValue.activities,\n configuration: stateValue.configuration,\n transitions: [],\n children: {}\n });\n }\n\n return State.from(stateValue, context);\n };\n /**\r\n * Returns an array of all the string leaf state node paths.\r\n * @param stateValue\r\n * @param delimiter The character(s) that separate each subpath in the string state node path.\r\n */\n\n\n State.prototype.toStrings = function (stateValue, delimiter) {\n var _this = this;\n\n if (stateValue === void 0) {\n stateValue = this.value;\n }\n\n if (delimiter === void 0) {\n delimiter = '.';\n }\n\n if (isString(stateValue)) {\n return [stateValue];\n }\n\n var valueKeys = Object.keys(stateValue);\n return valueKeys.concat.apply(valueKeys, __spreadArray([], __read(valueKeys.map(function (key) {\n return _this.toStrings(stateValue[key], delimiter).map(function (s) {\n return key + delimiter + s;\n });\n })), false));\n };\n\n State.prototype.toJSON = function () {\n var _a = this;\n _a.configuration;\n _a.transitions;\n var tags = _a.tags;\n _a.machine;\n var jsonValues = __rest(_a, [\"configuration\", \"transitions\", \"tags\", \"machine\"]);\n\n return __assign(__assign({}, jsonValues), {\n tags: Array.from(tags)\n });\n };\n\n State.prototype.matches = function (parentStateValue) {\n return matchesState(parentStateValue, this.value);\n };\n /**\r\n * Whether the current state configuration has a state node with the specified `tag`.\r\n * @param tag\r\n */\n\n\n State.prototype.hasTag = function (tag) {\n return this.tags.has(tag);\n };\n /**\r\n * Determines whether sending the `event` will cause a non-forbidden transition\r\n * to be selected, even if the transitions have no actions nor\r\n * change the state value.\r\n *\r\n * @param event The event to test\r\n * @returns Whether the event will cause a transition\r\n */\n\n\n State.prototype.can = function (event) {\n var _a;\n\n if (IS_PRODUCTION) {\n warn(!!this.machine, \"state.can(...) used outside of a machine-created State object; this will always return false.\");\n }\n\n var transitionData = (_a = this.machine) === null || _a === void 0 ? void 0 : _a.getTransitionData(this, event);\n return !!(transitionData === null || transitionData === void 0 ? void 0 : transitionData.transitions.length) && // Check that at least one transition is not forbidden\n transitionData.transitions.some(function (t) {\n return t.target !== undefined || t.actions.length;\n });\n };\n\n return State;\n}();\n\nexport { State, bindActionToState, isState, isStateConfig, stateValuesEqual };\n","import { __assign } from './_virtual/_tslib.js';\n\nvar defaultOptions = {\n deferEvents: false\n};\n\nvar Scheduler =\n/*#__PURE__*/\n\n/** @class */\nfunction () {\n function Scheduler(options) {\n this.processingEvent = false;\n this.queue = [];\n this.initialized = false;\n this.options = __assign(__assign({}, defaultOptions), options);\n }\n\n Scheduler.prototype.initialize = function (callback) {\n this.initialized = true;\n\n if (callback) {\n if (!this.options.deferEvents) {\n this.schedule(callback);\n return;\n }\n\n this.process(callback);\n }\n\n this.flushEvents();\n };\n\n Scheduler.prototype.schedule = function (task) {\n if (!this.initialized || this.processingEvent) {\n this.queue.push(task);\n return;\n }\n\n if (this.queue.length !== 0) {\n throw new Error('Event queue should be empty when it is not processing events');\n }\n\n this.process(task);\n this.flushEvents();\n };\n\n Scheduler.prototype.clear = function () {\n this.queue = [];\n };\n\n Scheduler.prototype.flushEvents = function () {\n var nextCallback = this.queue.shift();\n\n while (nextCallback) {\n this.process(nextCallback);\n nextCallback = this.queue.shift();\n }\n };\n\n Scheduler.prototype.process = function (callback) {\n this.processingEvent = true;\n\n try {\n callback();\n } catch (e) {\n // there is no use to keep the future events\n // as the situation is not anymore the same\n this.clear();\n throw e;\n } finally {\n this.processingEvent = false;\n }\n };\n\n return Scheduler;\n}();\n\nexport { Scheduler };\n","var children = /*#__PURE__*/new Map();\nvar sessionIdIndex = 0;\nvar registry = {\n bookId: function () {\n return \"x:\".concat(sessionIdIndex++);\n },\n register: function (id, actor) {\n children.set(id, actor);\n return id;\n },\n get: function (id) {\n return children.get(id);\n },\n free: function (id) {\n children.delete(id);\n }\n};\n\nexport { registry };\n","import { IS_PRODUCTION } from './environment.js';\n\nfunction getGlobal() {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n }\n\n if (typeof self !== 'undefined') {\n return self;\n }\n\n if (typeof window !== 'undefined') {\n return window;\n }\n\n if (typeof global !== 'undefined') {\n return global;\n }\n\n if (!IS_PRODUCTION) {\n console.warn('XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues');\n }\n}\n\nfunction getDevTools() {\n var global = getGlobal();\n\n if (global && '__xstate__' in global) {\n return global.__xstate__;\n }\n\n return undefined;\n}\n\nfunction registerService(service) {\n if (!getGlobal()) {\n return;\n }\n\n var devTools = getDevTools();\n\n if (devTools) {\n devTools.register(service);\n }\n}\n\nexport { getGlobal, registerService };\n","import { error, doneInvoke } from './actions.js';\nimport { toActorRef } from './Actor.js';\nimport { toObserver } from './utils.js';\n\n/**\r\n * Returns an actor behavior from a reducer and its initial state.\r\n *\r\n * @param transition The pure reducer that returns the next state given the current state and event.\r\n * @param initialState The initial state of the reducer.\r\n * @returns An actor behavior\r\n */\n\nfunction fromReducer(transition, initialState) {\n return {\n transition: transition,\n initialState: initialState\n };\n}\nfunction fromPromise(promiseFn) {\n var initialState = {\n error: undefined,\n data: undefined,\n status: 'pending'\n };\n return {\n transition: function (state, event, _a) {\n var parent = _a.parent,\n id = _a.id,\n observers = _a.observers;\n\n switch (event.type) {\n case 'fulfill':\n parent === null || parent === void 0 ? void 0 : parent.send(doneInvoke(id, event.data));\n return {\n error: undefined,\n data: event.data,\n status: 'fulfilled'\n };\n\n case 'reject':\n parent === null || parent === void 0 ? void 0 : parent.send(error(id, event.error));\n observers.forEach(function (observer) {\n observer.error(event.error);\n });\n return {\n error: event.error,\n data: undefined,\n status: 'rejected'\n };\n\n default:\n return state;\n }\n },\n initialState: initialState,\n start: function (_a) {\n var self = _a.self;\n promiseFn().then(function (data) {\n self.send({\n type: 'fulfill',\n data: data\n });\n }, function (reason) {\n self.send({\n type: 'reject',\n error: reason\n });\n });\n return initialState;\n }\n };\n}\nfunction spawnBehavior(behavior, options) {\n if (options === void 0) {\n options = {};\n }\n\n var state = behavior.initialState;\n var observers = new Set();\n var mailbox = [];\n var flushing = false;\n\n var flush = function () {\n if (flushing) {\n return;\n }\n\n flushing = true;\n\n while (mailbox.length > 0) {\n var event_1 = mailbox.shift();\n state = behavior.transition(state, event_1, actorCtx);\n observers.forEach(function (observer) {\n return observer.next(state);\n });\n }\n\n flushing = false;\n };\n\n var actor = toActorRef({\n id: options.id,\n send: function (event) {\n mailbox.push(event);\n flush();\n },\n getSnapshot: function () {\n return state;\n },\n subscribe: function (next, handleError, complete) {\n var observer = toObserver(next, handleError, complete);\n observers.add(observer);\n observer.next(state);\n return {\n unsubscribe: function () {\n observers.delete(observer);\n }\n };\n }\n });\n var actorCtx = {\n parent: options.parent,\n self: actor,\n id: options.id || 'anonymous',\n observers: observers\n };\n state = behavior.start ? behavior.start(actorCtx) : state;\n return actor;\n}\n\nexport { fromPromise, fromReducer, spawnBehavior };\n","import { __values, __spreadArray, __read, __assign } from './_virtual/_tslib.js';\nimport { SpecialTargets, ActionTypes } from './types.js';\nimport { isStateConfig, State, bindActionToState } from './State.js';\nimport { errorPlatform, update, error as error$1, log, stop, start, cancel, send, raise } from './actionTypes.js';\nimport { initEvent, doneInvoke, toActionObjects, resolveActions, error, getActionFunction } from './actions.js';\nimport { IS_PRODUCTION } from './environment.js';\nimport { warn, mapContext, toObserver, isFunction, toSCXMLEvent, flatten, isRaisableAction, isPromiseLike, isObservable, isMachine, isBehavior, reportUnhandledExceptionOnInvocation, symbolObservable, isArray, toEventObject, isString, isActor, toInvokeSource, uniqueId } from './utils.js';\nimport { Scheduler } from './scheduler.js';\nimport { createDeferredActor, isSpawnedActor } from './Actor.js';\nimport { registry } from './registry.js';\nimport { getGlobal, registerService } from './devTools.js';\nimport { provide, consume } from './serviceScope.js';\nimport { spawnBehavior } from './behaviors.js';\n\nvar DEFAULT_SPAWN_OPTIONS = {\n sync: false,\n autoForward: false\n};\nvar InterpreterStatus;\n\n(function (InterpreterStatus) {\n InterpreterStatus[InterpreterStatus[\"NotStarted\"] = 0] = \"NotStarted\";\n InterpreterStatus[InterpreterStatus[\"Running\"] = 1] = \"Running\";\n InterpreterStatus[InterpreterStatus[\"Stopped\"] = 2] = \"Stopped\";\n})(InterpreterStatus || (InterpreterStatus = {}));\n\nvar Interpreter =\n/*#__PURE__*/\n\n/** @class */\nfunction () {\n /**\r\n * Creates a new Interpreter instance (i.e., service) for the given machine with the provided options, if any.\r\n *\r\n * @param machine The machine to be interpreted\r\n * @param options Interpreter options\r\n */\n function Interpreter(machine, options) {\n if (options === void 0) {\n options = Interpreter.defaultOptions;\n }\n\n var _this = this;\n\n this.machine = machine;\n this.delayedEventsMap = {};\n this.listeners = new Set();\n this.contextListeners = new Set();\n this.stopListeners = new Set();\n this.doneListeners = new Set();\n this.eventListeners = new Set();\n this.sendListeners = new Set();\n /**\r\n * Whether the service is started.\r\n */\n\n this.initialized = false;\n this.status = InterpreterStatus.NotStarted;\n this.children = new Map();\n this.forwardTo = new Set();\n this._outgoingQueue = [];\n /**\r\n * Alias for Interpreter.prototype.start\r\n */\n\n this.init = this.start;\n /**\r\n * Sends an event to the running interpreter to trigger a transition.\r\n *\r\n * An array of events (batched) can be sent as well, which will send all\r\n * batched events to the running interpreter. The listeners will be\r\n * notified only **once** when all events are processed.\r\n *\r\n * @param event The event(s) to send\r\n */\n\n this.send = function (event, payload) {\n if (isArray(event)) {\n _this.batch(event);\n\n return _this.state;\n }\n\n var _event = toSCXMLEvent(toEventObject(event, payload));\n\n if (_this.status === InterpreterStatus.Stopped) {\n // do nothing\n if (!IS_PRODUCTION) {\n warn(false, \"Event \\\"\".concat(_event.name, \"\\\" was sent to stopped service \\\"\").concat(_this.machine.id, \"\\\". This service has already reached its final state, and will not transition.\\nEvent: \").concat(JSON.stringify(_event.data)));\n }\n\n return _this.state;\n }\n\n if (_this.status !== InterpreterStatus.Running && !_this.options.deferEvents) {\n throw new Error(\"Event \\\"\".concat(_event.name, \"\\\" was sent to uninitialized service \\\"\").concat(_this.machine.id // tslint:disable-next-line:max-line-length\n , \"\\\". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.\\nEvent: \").concat(JSON.stringify(_event.data)));\n }\n\n _this.scheduler.schedule(function () {\n // Forward copy of event to child actors\n _this.forward(_event);\n\n var nextState = _this._nextState(_event);\n\n _this.update(nextState, _event);\n });\n\n return _this._state; // TODO: deprecate (should return void)\n // tslint:disable-next-line:semicolon\n };\n\n this.sendTo = function (event, to, immediate) {\n var isParent = _this.parent && (to === SpecialTargets.Parent || _this.parent.id === to);\n var target = isParent ? _this.parent : isString(to) ? to === SpecialTargets.Internal ? _this : _this.children.get(to) || registry.get(to) : isActor(to) ? to : undefined;\n\n if (!target) {\n if (!isParent) {\n throw new Error(\"Unable to send event to child '\".concat(to, \"' from service '\").concat(_this.id, \"'.\"));\n } // tslint:disable-next-line:no-console\n\n\n if (!IS_PRODUCTION) {\n warn(false, \"Service '\".concat(_this.id, \"' has no parent: unable to send event \").concat(event.type));\n }\n\n return;\n }\n\n if ('machine' in target) {\n // perhaps those events should be rejected in the parent\n // but atm it doesn't have easy access to all of the information that is required to do it reliably\n if (_this.status !== InterpreterStatus.Stopped || _this.parent !== target || // we need to send events to the parent from exit handlers of a machine that reached its final state\n _this.state.done) {\n // Send SCXML events to machines\n var scxmlEvent = __assign(__assign({}, event), {\n name: event.name === error$1 ? \"\".concat(error(_this.id)) : event.name,\n origin: _this.sessionId\n });\n\n if (!immediate && _this.machine.config.predictableActionArguments) {\n _this._outgoingQueue.push([target, scxmlEvent]);\n } else {\n target.send(scxmlEvent);\n }\n }\n } else {\n // Send normal events to other targets\n if (!immediate && _this.machine.config.predictableActionArguments) {\n _this._outgoingQueue.push([target, event.data]);\n } else {\n target.send(event.data);\n }\n }\n };\n\n this._exec = function (action, context, _event, actionFunctionMap) {\n if (actionFunctionMap === void 0) {\n actionFunctionMap = _this.machine.options.actions;\n }\n\n var actionOrExec = action.exec || getActionFunction(action.type, actionFunctionMap);\n var exec = isFunction(actionOrExec) ? actionOrExec : actionOrExec ? actionOrExec.exec : action.exec;\n\n if (exec) {\n try {\n return exec(context, _event.data, !_this.machine.config.predictableActionArguments ? {\n action: action,\n state: _this.state,\n _event: _event\n } : {\n action: action,\n _event: _event\n });\n } catch (err) {\n if (_this.parent) {\n _this.parent.send({\n type: 'xstate.error',\n data: err\n });\n }\n\n throw err;\n }\n }\n\n switch (action.type) {\n case raise:\n {\n // if raise action reached the interpreter then it's a delayed one\n var sendAction_1 = action;\n\n _this.defer(sendAction_1);\n\n break;\n }\n\n case send:\n var sendAction = action;\n\n if (typeof sendAction.delay === 'number') {\n _this.defer(sendAction);\n\n return;\n } else {\n if (sendAction.to) {\n _this.sendTo(sendAction._event, sendAction.to, _event === initEvent);\n } else {\n _this.send(sendAction._event);\n }\n }\n\n break;\n\n case cancel:\n _this.cancel(action.sendId);\n\n break;\n\n case start:\n {\n if (_this.status !== InterpreterStatus.Running) {\n return;\n }\n\n var activity = action.activity; // If the activity will be stopped right after it's started\n // (such as in transient states)\n // don't bother starting the activity.\n\n if ( // in v4 with `predictableActionArguments` invokes are called eagerly when the `this.state` still points to the previous state\n !_this.machine.config.predictableActionArguments && !_this.state.activities[activity.id || activity.type]) {\n break;\n } // Invoked services\n\n\n if (activity.type === ActionTypes.Invoke) {\n var invokeSource = toInvokeSource(activity.src);\n var serviceCreator = _this.machine.options.services ? _this.machine.options.services[invokeSource.type] : undefined;\n var id = activity.id,\n data = activity.data;\n\n if (!IS_PRODUCTION) {\n warn(!('forward' in activity), // tslint:disable-next-line:max-line-length\n \"`forward` property is deprecated (found in invocation of '\".concat(activity.src, \"' in in machine '\").concat(_this.machine.id, \"'). \") + \"Please use `autoForward` instead.\");\n }\n\n var autoForward = 'autoForward' in activity ? activity.autoForward : !!activity.forward;\n\n if (!serviceCreator) {\n // tslint:disable-next-line:no-console\n if (!IS_PRODUCTION) {\n warn(false, \"No service found for invocation '\".concat(activity.src, \"' in machine '\").concat(_this.machine.id, \"'.\"));\n }\n\n return;\n }\n\n var resolvedData = data ? mapContext(data, context, _event) : undefined;\n\n if (typeof serviceCreator === 'string') {\n // TODO: warn\n return;\n }\n\n var source = isFunction(serviceCreator) ? serviceCreator(context, _event.data, {\n data: resolvedData,\n src: invokeSource,\n meta: activity.meta\n }) : serviceCreator;\n\n if (!source) {\n // TODO: warn?\n return;\n }\n\n var options = void 0;\n\n if (isMachine(source)) {\n source = resolvedData ? source.withContext(resolvedData) : source;\n options = {\n autoForward: autoForward\n };\n }\n\n _this.spawn(source, id, options);\n } else {\n _this.spawnActivity(activity);\n }\n\n break;\n }\n\n case stop:\n {\n _this.stopChild(action.activity.id);\n\n break;\n }\n\n case log:\n var _a = action,\n label = _a.label,\n value = _a.value;\n\n if (label) {\n _this.logger(label, value);\n } else {\n _this.logger(value);\n }\n\n break;\n\n default:\n if (!IS_PRODUCTION) {\n warn(false, \"No implementation found for action type '\".concat(action.type, \"'\"));\n }\n\n break;\n }\n };\n\n var resolvedOptions = __assign(__assign({}, Interpreter.defaultOptions), options);\n\n var clock = resolvedOptions.clock,\n logger = resolvedOptions.logger,\n parent = resolvedOptions.parent,\n id = resolvedOptions.id;\n var resolvedId = id !== undefined ? id : machine.id;\n this.id = resolvedId;\n this.logger = logger;\n this.clock = clock;\n this.parent = parent;\n this.options = resolvedOptions;\n this.scheduler = new Scheduler({\n deferEvents: this.options.deferEvents\n });\n this.sessionId = registry.bookId();\n }\n\n Object.defineProperty(Interpreter.prototype, \"initialState\", {\n get: function () {\n var _this = this;\n\n if (this._initialState) {\n return this._initialState;\n }\n\n return provide(this, function () {\n _this._initialState = _this.machine.initialState;\n return _this._initialState;\n });\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Interpreter.prototype, \"state\", {\n /**\r\n * @deprecated Use `.getSnapshot()` instead.\r\n */\n get: function () {\n if (!IS_PRODUCTION) {\n warn(this.status !== InterpreterStatus.NotStarted, \"Attempted to read state from uninitialized service '\".concat(this.id, \"'. Make sure the service is started first.\"));\n }\n\n return this._state;\n },\n enumerable: false,\n configurable: true\n });\n /**\r\n * Executes the actions of the given state, with that state's `context` and `event`.\r\n *\r\n * @param state The state whose actions will be executed\r\n * @param actionsConfig The action implementations to use\r\n */\n\n Interpreter.prototype.execute = function (state, actionsConfig) {\n var e_1, _a;\n\n try {\n for (var _b = __values(state.actions), _c = _b.next(); !_c.done; _c = _b.next()) {\n var action = _c.value;\n this.exec(action, state, actionsConfig);\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n };\n\n Interpreter.prototype.update = function (state, _event) {\n var e_2, _a, e_3, _b, e_4, _c, e_5, _d;\n\n var _this = this; // Attach session ID to state\n\n\n state._sessionid = this.sessionId; // Update state\n\n this._state = state; // Execute actions\n\n if ((!this.machine.config.predictableActionArguments || // this is currently required to execute initial actions as the `initialState` gets cached\n // we can't just recompute it (and execute actions while doing so) because we try to preserve identity of actors created within initial assigns\n _event === initEvent) && this.options.execute) {\n this.execute(this.state);\n } else {\n var item = void 0;\n\n while (item = this._outgoingQueue.shift()) {\n item[0].send(item[1]);\n }\n } // Update children\n\n\n this.children.forEach(function (child) {\n _this.state.children[child.id] = child;\n }); // Dev tools\n\n if (this.devTools) {\n this.devTools.send(_event.data, state);\n } // Execute listeners\n\n\n if (state.event) {\n try {\n for (var _e = __values(this.eventListeners), _f = _e.next(); !_f.done; _f = _e.next()) {\n var listener = _f.value;\n listener(state.event);\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (_f && !_f.done && (_a = _e.return)) _a.call(_e);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n }\n\n try {\n for (var _g = __values(this.listeners), _h = _g.next(); !_h.done; _h = _g.next()) {\n var listener = _h.value;\n listener(state, state.event);\n }\n } catch (e_3_1) {\n e_3 = {\n error: e_3_1\n };\n } finally {\n try {\n if (_h && !_h.done && (_b = _g.return)) _b.call(_g);\n } finally {\n if (e_3) throw e_3.error;\n }\n }\n\n try {\n for (var _j = __values(this.contextListeners), _k = _j.next(); !_k.done; _k = _j.next()) {\n var contextListener = _k.value;\n contextListener(this.state.context, this.state.history ? this.state.history.context : undefined);\n }\n } catch (e_4_1) {\n e_4 = {\n error: e_4_1\n };\n } finally {\n try {\n if (_k && !_k.done && (_c = _j.return)) _c.call(_j);\n } finally {\n if (e_4) throw e_4.error;\n }\n }\n\n if (this.state.done) {\n // get final child state node\n var finalChildStateNode = state.configuration.find(function (sn) {\n return sn.type === 'final' && sn.parent === _this.machine;\n });\n var doneData = finalChildStateNode && finalChildStateNode.doneData ? mapContext(finalChildStateNode.doneData, state.context, _event) : undefined;\n this._doneEvent = doneInvoke(this.id, doneData);\n\n try {\n for (var _l = __values(this.doneListeners), _m = _l.next(); !_m.done; _m = _l.next()) {\n var listener = _m.value;\n listener(this._doneEvent);\n }\n } catch (e_5_1) {\n e_5 = {\n error: e_5_1\n };\n } finally {\n try {\n if (_m && !_m.done && (_d = _l.return)) _d.call(_l);\n } finally {\n if (e_5) throw e_5.error;\n }\n }\n\n this._stop();\n\n this._stopChildren();\n\n registry.free(this.sessionId);\n }\n };\n /*\r\n * Adds a listener that is notified whenever a state transition happens. The listener is called with\r\n * the next state and the event object that caused the state transition.\r\n *\r\n * @param listener The state listener\r\n */\n\n\n Interpreter.prototype.onTransition = function (listener) {\n this.listeners.add(listener); // Send current state to listener\n\n if (this.status === InterpreterStatus.Running) {\n listener(this.state, this.state.event);\n }\n\n return this;\n };\n\n Interpreter.prototype.subscribe = function (nextListenerOrObserver, _, // TODO: error listener\n completeListener) {\n var _this = this;\n\n var observer = toObserver(nextListenerOrObserver, _, completeListener);\n this.listeners.add(observer.next); // Send current state to listener\n\n if (this.status !== InterpreterStatus.NotStarted) {\n observer.next(this.state);\n }\n\n var completeOnce = function () {\n _this.doneListeners.delete(completeOnce);\n\n _this.stopListeners.delete(completeOnce);\n\n observer.complete();\n };\n\n if (this.status === InterpreterStatus.Stopped) {\n observer.complete();\n } else {\n this.onDone(completeOnce);\n this.onStop(completeOnce);\n }\n\n return {\n unsubscribe: function () {\n _this.listeners.delete(observer.next);\n\n _this.doneListeners.delete(completeOnce);\n\n _this.stopListeners.delete(completeOnce);\n }\n };\n };\n /**\r\n * Adds an event listener that is notified whenever an event is sent to the running interpreter.\r\n * @param listener The event listener\r\n */\n\n\n Interpreter.prototype.onEvent = function (listener) {\n this.eventListeners.add(listener);\n return this;\n };\n /**\r\n * Adds an event listener that is notified whenever a `send` event occurs.\r\n * @param listener The event listener\r\n */\n\n\n Interpreter.prototype.onSend = function (listener) {\n this.sendListeners.add(listener);\n return this;\n };\n /**\r\n * Adds a context listener that is notified whenever the state context changes.\r\n * @param listener The context listener\r\n */\n\n\n Interpreter.prototype.onChange = function (listener) {\n this.contextListeners.add(listener);\n return this;\n };\n /**\r\n * Adds a listener that is notified when the machine is stopped.\r\n * @param listener The listener\r\n */\n\n\n Interpreter.prototype.onStop = function (listener) {\n this.stopListeners.add(listener);\n return this;\n };\n /**\r\n * Adds a state listener that is notified when the statechart has reached its final state.\r\n * @param listener The state listener\r\n */\n\n\n Interpreter.prototype.onDone = function (listener) {\n if (this.status === InterpreterStatus.Stopped && this._doneEvent) {\n listener(this._doneEvent);\n } else {\n this.doneListeners.add(listener);\n }\n\n return this;\n };\n /**\r\n * Removes a listener.\r\n * @param listener The listener to remove\r\n */\n\n\n Interpreter.prototype.off = function (listener) {\n this.listeners.delete(listener);\n this.eventListeners.delete(listener);\n this.sendListeners.delete(listener);\n this.stopListeners.delete(listener);\n this.doneListeners.delete(listener);\n this.contextListeners.delete(listener);\n return this;\n };\n /**\r\n * Starts the interpreter from the given state, or the initial state.\r\n * @param initialState The state to start the statechart from\r\n */\n\n\n Interpreter.prototype.start = function (initialState) {\n var _this = this;\n\n if (this.status === InterpreterStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n } // yes, it's a hack but we need the related cache to be populated for some things to work (like delayed transitions)\n // this is usually called by `machine.getInitialState` but if we rehydrate from a state we might bypass this call\n // we also don't want to call this method here as it resolves the full initial state which might involve calling assign actions\n // and that could potentially lead to some unwanted side-effects (even such as creating some rogue actors)\n\n\n this.machine._init();\n\n registry.register(this.sessionId, this);\n this.initialized = true;\n this.status = InterpreterStatus.Running;\n var resolvedState = initialState === undefined ? this.initialState : provide(this, function () {\n return isStateConfig(initialState) ? _this.machine.resolveState(initialState) : _this.machine.resolveState(State.from(initialState, _this.machine.context));\n });\n\n if (this.options.devTools) {\n this.attachDev();\n }\n\n this.scheduler.initialize(function () {\n _this.update(resolvedState, initEvent);\n });\n return this;\n };\n\n Interpreter.prototype._stopChildren = function () {\n // TODO: think about converting those to actions\n this.children.forEach(function (child) {\n if (isFunction(child.stop)) {\n child.stop();\n }\n });\n this.children.clear();\n };\n\n Interpreter.prototype._stop = function () {\n var e_6, _a, e_7, _b, e_8, _c, e_9, _d, e_10, _e;\n\n try {\n for (var _f = __values(this.listeners), _g = _f.next(); !_g.done; _g = _f.next()) {\n var listener = _g.value;\n this.listeners.delete(listener);\n }\n } catch (e_6_1) {\n e_6 = {\n error: e_6_1\n };\n } finally {\n try {\n if (_g && !_g.done && (_a = _f.return)) _a.call(_f);\n } finally {\n if (e_6) throw e_6.error;\n }\n }\n\n try {\n for (var _h = __values(this.stopListeners), _j = _h.next(); !_j.done; _j = _h.next()) {\n var listener = _j.value; // call listener, then remove\n\n listener();\n this.stopListeners.delete(listener);\n }\n } catch (e_7_1) {\n e_7 = {\n error: e_7_1\n };\n } finally {\n try {\n if (_j && !_j.done && (_b = _h.return)) _b.call(_h);\n } finally {\n if (e_7) throw e_7.error;\n }\n }\n\n try {\n for (var _k = __values(this.contextListeners), _l = _k.next(); !_l.done; _l = _k.next()) {\n var listener = _l.value;\n this.contextListeners.delete(listener);\n }\n } catch (e_8_1) {\n e_8 = {\n error: e_8_1\n };\n } finally {\n try {\n if (_l && !_l.done && (_c = _k.return)) _c.call(_k);\n } finally {\n if (e_8) throw e_8.error;\n }\n }\n\n try {\n for (var _m = __values(this.doneListeners), _o = _m.next(); !_o.done; _o = _m.next()) {\n var listener = _o.value;\n this.doneListeners.delete(listener);\n }\n } catch (e_9_1) {\n e_9 = {\n error: e_9_1\n };\n } finally {\n try {\n if (_o && !_o.done && (_d = _m.return)) _d.call(_m);\n } finally {\n if (e_9) throw e_9.error;\n }\n }\n\n if (!this.initialized) {\n // Interpreter already stopped; do nothing\n return this;\n }\n\n this.initialized = false;\n this.status = InterpreterStatus.Stopped;\n this._initialState = undefined;\n\n try {\n // we are going to stop within the current sync frame\n // so we can safely just cancel this here as nothing async should be fired anyway\n for (var _p = __values(Object.keys(this.delayedEventsMap)), _q = _p.next(); !_q.done; _q = _p.next()) {\n var key = _q.value;\n this.clock.clearTimeout(this.delayedEventsMap[key]);\n }\n } catch (e_10_1) {\n e_10 = {\n error: e_10_1\n };\n } finally {\n try {\n if (_q && !_q.done && (_e = _p.return)) _e.call(_p);\n } finally {\n if (e_10) throw e_10.error;\n }\n } // clear everything that might be enqueued\n\n\n this.scheduler.clear();\n this.scheduler = new Scheduler({\n deferEvents: this.options.deferEvents\n });\n };\n /**\r\n * Stops the interpreter and unsubscribe all listeners.\r\n *\r\n * This will also notify the `onStop` listeners.\r\n */\n\n\n Interpreter.prototype.stop = function () {\n // TODO: add warning for stopping non-root interpreters\n var _this = this; // grab the current scheduler as it will be replaced in _stop\n\n\n var scheduler = this.scheduler;\n\n this._stop(); // let what is currently processed to be finished\n\n\n scheduler.schedule(function () {\n // it feels weird to handle this here but we need to handle this even slightly \"out of band\"\n var _event = toSCXMLEvent({\n type: 'xstate.stop'\n });\n\n var nextState = provide(_this, function () {\n var exitActions = flatten(__spreadArray([], __read(_this.state.configuration), false).sort(function (a, b) {\n return b.order - a.order;\n }).map(function (stateNode) {\n return toActionObjects(stateNode.onExit, _this.machine.options.actions);\n }));\n\n var _a = __read(resolveActions(_this.machine, _this.state, _this.state.context, _event, [{\n type: 'exit',\n actions: exitActions\n }], _this.machine.config.predictableActionArguments ? _this._exec : undefined, _this.machine.config.predictableActionArguments || _this.machine.config.preserveActionOrder), 2),\n resolvedActions = _a[0],\n updatedContext = _a[1];\n\n var newState = new State({\n value: _this.state.value,\n context: updatedContext,\n _event: _event,\n _sessionid: _this.sessionId,\n historyValue: undefined,\n history: _this.state,\n actions: resolvedActions.filter(function (action) {\n return !isRaisableAction(action);\n }),\n activities: {},\n events: [],\n configuration: [],\n transitions: [],\n children: {},\n done: _this.state.done,\n tags: _this.state.tags,\n machine: _this.machine\n });\n newState.changed = true;\n return newState;\n });\n\n _this.update(nextState, _event);\n\n _this._stopChildren();\n\n registry.free(_this.sessionId);\n });\n return this;\n };\n\n Interpreter.prototype.batch = function (events) {\n var _this = this;\n\n if (this.status === InterpreterStatus.NotStarted && this.options.deferEvents) {\n // tslint:disable-next-line:no-console\n if (!IS_PRODUCTION) {\n warn(false, \"\".concat(events.length, \" event(s) were sent to uninitialized service \\\"\").concat(this.machine.id, \"\\\" and are deferred. Make sure .start() is called for this service.\\nEvent: \").concat(JSON.stringify(event)));\n }\n } else if (this.status !== InterpreterStatus.Running) {\n throw new Error( // tslint:disable-next-line:max-line-length\n \"\".concat(events.length, \" event(s) were sent to uninitialized service \\\"\").concat(this.machine.id, \"\\\". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.\"));\n }\n\n if (!events.length) {\n return;\n }\n\n var exec = !!this.machine.config.predictableActionArguments && this._exec;\n this.scheduler.schedule(function () {\n var e_11, _a;\n\n var nextState = _this.state;\n var batchChanged = false;\n var batchedActions = [];\n\n var _loop_1 = function (event_1) {\n var _event = toSCXMLEvent(event_1);\n\n _this.forward(_event);\n\n nextState = provide(_this, function () {\n return _this.machine.transition(nextState, _event, undefined, exec || undefined);\n });\n batchedActions.push.apply(batchedActions, __spreadArray([], __read(_this.machine.config.predictableActionArguments ? nextState.actions : nextState.actions.map(function (a) {\n return bindActionToState(a, nextState);\n })), false));\n batchChanged = batchChanged || !!nextState.changed;\n };\n\n try {\n for (var events_1 = __values(events), events_1_1 = events_1.next(); !events_1_1.done; events_1_1 = events_1.next()) {\n var event_1 = events_1_1.value;\n\n _loop_1(event_1);\n }\n } catch (e_11_1) {\n e_11 = {\n error: e_11_1\n };\n } finally {\n try {\n if (events_1_1 && !events_1_1.done && (_a = events_1.return)) _a.call(events_1);\n } finally {\n if (e_11) throw e_11.error;\n }\n }\n\n nextState.changed = batchChanged;\n nextState.actions = batchedActions;\n\n _this.update(nextState, toSCXMLEvent(events[events.length - 1]));\n });\n };\n /**\r\n * Returns a send function bound to this interpreter instance.\r\n *\r\n * @param event The event to be sent by the sender.\r\n */\n\n\n Interpreter.prototype.sender = function (event) {\n return this.send.bind(this, event);\n };\n\n Interpreter.prototype._nextState = function (event, exec) {\n var _this = this;\n\n if (exec === void 0) {\n exec = !!this.machine.config.predictableActionArguments && this._exec;\n }\n\n var _event = toSCXMLEvent(event);\n\n if (_event.name.indexOf(errorPlatform) === 0 && !this.state.nextEvents.some(function (nextEvent) {\n return nextEvent.indexOf(errorPlatform) === 0;\n })) {\n throw _event.data.data;\n }\n\n var nextState = provide(this, function () {\n return _this.machine.transition(_this.state, _event, undefined, exec || undefined);\n });\n return nextState;\n };\n /**\r\n * Returns the next state given the interpreter's current state and the event.\r\n *\r\n * This is a pure method that does _not_ update the interpreter's state.\r\n *\r\n * @param event The event to determine the next state\r\n */\n\n\n Interpreter.prototype.nextState = function (event) {\n return this._nextState(event, false);\n };\n\n Interpreter.prototype.forward = function (event) {\n var e_12, _a;\n\n try {\n for (var _b = __values(this.forwardTo), _c = _b.next(); !_c.done; _c = _b.next()) {\n var id = _c.value;\n var child = this.children.get(id);\n\n if (!child) {\n throw new Error(\"Unable to forward event '\".concat(event, \"' from interpreter '\").concat(this.id, \"' to nonexistant child '\").concat(id, \"'.\"));\n }\n\n child.send(event);\n }\n } catch (e_12_1) {\n e_12 = {\n error: e_12_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_12) throw e_12.error;\n }\n }\n };\n\n Interpreter.prototype.defer = function (sendAction) {\n var _this = this;\n\n var timerId = this.clock.setTimeout(function () {\n if ('to' in sendAction && sendAction.to) {\n _this.sendTo(sendAction._event, sendAction.to, true);\n } else {\n _this.send(sendAction._event);\n }\n }, sendAction.delay);\n\n if (sendAction.id) {\n this.delayedEventsMap[sendAction.id] = timerId;\n }\n };\n\n Interpreter.prototype.cancel = function (sendId) {\n this.clock.clearTimeout(this.delayedEventsMap[sendId]);\n delete this.delayedEventsMap[sendId];\n };\n\n Interpreter.prototype.exec = function (action, state, actionFunctionMap) {\n if (actionFunctionMap === void 0) {\n actionFunctionMap = this.machine.options.actions;\n }\n\n this._exec(action, state.context, state._event, actionFunctionMap);\n };\n\n Interpreter.prototype.removeChild = function (childId) {\n var _a;\n\n this.children.delete(childId);\n this.forwardTo.delete(childId); // this.state might not exist at the time this is called,\n // such as when a child is added then removed while initializing the state\n\n (_a = this.state) === null || _a === void 0 ? true : delete _a.children[childId];\n };\n\n Interpreter.prototype.stopChild = function (childId) {\n var child = this.children.get(childId);\n\n if (!child) {\n return;\n }\n\n this.removeChild(childId);\n\n if (isFunction(child.stop)) {\n child.stop();\n }\n };\n\n Interpreter.prototype.spawn = function (entity, name, options) {\n if (this.status !== InterpreterStatus.Running) {\n return createDeferredActor(entity, name);\n }\n\n if (isPromiseLike(entity)) {\n return this.spawnPromise(Promise.resolve(entity), name);\n } else if (isFunction(entity)) {\n return this.spawnCallback(entity, name);\n } else if (isSpawnedActor(entity)) {\n return this.spawnActor(entity, name);\n } else if (isObservable(entity)) {\n return this.spawnObservable(entity, name);\n } else if (isMachine(entity)) {\n return this.spawnMachine(entity, __assign(__assign({}, options), {\n id: name\n }));\n } else if (isBehavior(entity)) {\n return this.spawnBehavior(entity, name);\n } else {\n throw new Error(\"Unable to spawn entity \\\"\".concat(name, \"\\\" of type \\\"\").concat(typeof entity, \"\\\".\"));\n }\n };\n\n Interpreter.prototype.spawnMachine = function (machine, options) {\n var _this = this;\n\n if (options === void 0) {\n options = {};\n }\n\n var childService = new Interpreter(machine, __assign(__assign({}, this.options), {\n parent: this,\n id: options.id || machine.id\n }));\n\n var resolvedOptions = __assign(__assign({}, DEFAULT_SPAWN_OPTIONS), options);\n\n if (resolvedOptions.sync) {\n childService.onTransition(function (state) {\n _this.send(update, {\n state: state,\n id: childService.id\n });\n });\n }\n\n var actor = childService;\n this.children.set(childService.id, actor);\n\n if (resolvedOptions.autoForward) {\n this.forwardTo.add(childService.id);\n }\n\n childService.onDone(function (doneEvent) {\n _this.removeChild(childService.id);\n\n _this.send(toSCXMLEvent(doneEvent, {\n origin: childService.id\n }));\n }).start();\n return actor;\n };\n\n Interpreter.prototype.spawnBehavior = function (behavior, id) {\n var actorRef = spawnBehavior(behavior, {\n id: id,\n parent: this\n });\n this.children.set(id, actorRef);\n return actorRef;\n };\n\n Interpreter.prototype.spawnPromise = function (promise, id) {\n var _a;\n\n var _this = this;\n\n var canceled = false;\n var resolvedData;\n promise.then(function (response) {\n if (!canceled) {\n resolvedData = response;\n\n _this.removeChild(id);\n\n _this.send(toSCXMLEvent(doneInvoke(id, response), {\n origin: id\n }));\n }\n }, function (errorData) {\n if (!canceled) {\n _this.removeChild(id);\n\n var errorEvent = error(id, errorData);\n\n try {\n // Send \"error.platform.id\" to this (parent).\n _this.send(toSCXMLEvent(errorEvent, {\n origin: id\n }));\n } catch (error) {\n reportUnhandledExceptionOnInvocation(errorData, error, id);\n\n if (_this.devTools) {\n _this.devTools.send(errorEvent, _this.state);\n }\n\n if (_this.machine.strict) {\n // it would be better to always stop the state machine if unhandled\n // exception/promise rejection happens but because we don't want to\n // break existing code so enforce it on strict mode only especially so\n // because documentation says that onError is optional\n _this.stop();\n }\n }\n }\n });\n var actor = (_a = {\n id: id,\n send: function () {\n return void 0;\n },\n subscribe: function (next, handleError, complete) {\n var observer = toObserver(next, handleError, complete);\n var unsubscribed = false;\n promise.then(function (response) {\n if (unsubscribed) {\n return;\n }\n\n observer.next(response);\n\n if (unsubscribed) {\n return;\n }\n\n observer.complete();\n }, function (err) {\n if (unsubscribed) {\n return;\n }\n\n observer.error(err);\n });\n return {\n unsubscribe: function () {\n return unsubscribed = true;\n }\n };\n },\n stop: function () {\n canceled = true;\n },\n toJSON: function () {\n return {\n id: id\n };\n },\n getSnapshot: function () {\n return resolvedData;\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a);\n this.children.set(id, actor);\n return actor;\n };\n\n Interpreter.prototype.spawnCallback = function (callback, id) {\n var _a;\n\n var _this = this;\n\n var canceled = false;\n var receivers = new Set();\n var listeners = new Set();\n var emitted;\n\n var receive = function (e) {\n emitted = e;\n listeners.forEach(function (listener) {\n return listener(e);\n });\n\n if (canceled) {\n return;\n }\n\n _this.send(toSCXMLEvent(e, {\n origin: id\n }));\n };\n\n var callbackStop;\n\n try {\n callbackStop = callback(receive, function (newListener) {\n receivers.add(newListener);\n });\n } catch (err) {\n this.send(error(id, err));\n }\n\n if (isPromiseLike(callbackStop)) {\n // it turned out to be an async function, can't reliably check this before calling `callback`\n // because transpiled async functions are not recognizable\n return this.spawnPromise(callbackStop, id);\n }\n\n var actor = (_a = {\n id: id,\n send: function (event) {\n return receivers.forEach(function (receiver) {\n return receiver(event);\n });\n },\n subscribe: function (next) {\n var observer = toObserver(next);\n listeners.add(observer.next);\n return {\n unsubscribe: function () {\n listeners.delete(observer.next);\n }\n };\n },\n stop: function () {\n canceled = true;\n\n if (isFunction(callbackStop)) {\n callbackStop();\n }\n },\n toJSON: function () {\n return {\n id: id\n };\n },\n getSnapshot: function () {\n return emitted;\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a);\n this.children.set(id, actor);\n return actor;\n };\n\n Interpreter.prototype.spawnObservable = function (source, id) {\n var _a;\n\n var _this = this;\n\n var emitted;\n var subscription = source.subscribe(function (value) {\n emitted = value;\n\n _this.send(toSCXMLEvent(value, {\n origin: id\n }));\n }, function (err) {\n _this.removeChild(id);\n\n _this.send(toSCXMLEvent(error(id, err), {\n origin: id\n }));\n }, function () {\n _this.removeChild(id);\n\n _this.send(toSCXMLEvent(doneInvoke(id), {\n origin: id\n }));\n });\n var actor = (_a = {\n id: id,\n send: function () {\n return void 0;\n },\n subscribe: function (next, handleError, complete) {\n return source.subscribe(next, handleError, complete);\n },\n stop: function () {\n return subscription.unsubscribe();\n },\n getSnapshot: function () {\n return emitted;\n },\n toJSON: function () {\n return {\n id: id\n };\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a);\n this.children.set(id, actor);\n return actor;\n };\n\n Interpreter.prototype.spawnActor = function (actor, name) {\n this.children.set(name, actor);\n return actor;\n };\n\n Interpreter.prototype.spawnActivity = function (activity) {\n var implementation = this.machine.options && this.machine.options.activities ? this.machine.options.activities[activity.type] : undefined;\n\n if (!implementation) {\n if (!IS_PRODUCTION) {\n warn(false, \"No implementation found for activity '\".concat(activity.type, \"'\"));\n } // tslint:disable-next-line:no-console\n\n\n return;\n } // Start implementation\n\n\n var dispose = implementation(this.state.context, activity);\n this.spawnEffect(activity.id, dispose);\n };\n\n Interpreter.prototype.spawnEffect = function (id, dispose) {\n var _a;\n\n this.children.set(id, (_a = {\n id: id,\n send: function () {\n return void 0;\n },\n subscribe: function () {\n return {\n unsubscribe: function () {\n return void 0;\n }\n };\n },\n stop: dispose || undefined,\n getSnapshot: function () {\n return undefined;\n },\n toJSON: function () {\n return {\n id: id\n };\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a));\n };\n\n Interpreter.prototype.attachDev = function () {\n var global = getGlobal();\n\n if (this.options.devTools && global) {\n if (global.__REDUX_DEVTOOLS_EXTENSION__) {\n var devToolsOptions = typeof this.options.devTools === 'object' ? this.options.devTools : undefined;\n this.devTools = global.__REDUX_DEVTOOLS_EXTENSION__.connect(__assign(__assign({\n name: this.id,\n autoPause: true,\n stateSanitizer: function (state) {\n return {\n value: state.value,\n context: state.context,\n actions: state.actions\n };\n }\n }, devToolsOptions), {\n features: __assign({\n jump: false,\n skip: false\n }, devToolsOptions ? devToolsOptions.features : undefined)\n }), this.machine);\n this.devTools.init(this.state);\n } // add XState-specific dev tooling hook\n\n\n registerService(this);\n }\n };\n\n Interpreter.prototype.toJSON = function () {\n return {\n id: this.id\n };\n };\n\n Interpreter.prototype[symbolObservable] = function () {\n return this;\n };\n\n Interpreter.prototype.getSnapshot = function () {\n if (this.status === InterpreterStatus.NotStarted) {\n return this.initialState;\n }\n\n return this._state;\n };\n /**\r\n * The default interpreter options:\r\n *\r\n * - `clock` uses the global `setTimeout` and `clearTimeout` functions\r\n * - `logger` uses the global `console.log()` method\r\n */\n\n\n Interpreter.defaultOptions = {\n execute: true,\n deferEvents: true,\n clock: {\n setTimeout: function (fn, ms) {\n return setTimeout(fn, ms);\n },\n clearTimeout: function (id) {\n return clearTimeout(id);\n }\n },\n logger: /*#__PURE__*/console.log.bind(console),\n devTools: false\n };\n Interpreter.interpret = interpret;\n return Interpreter;\n}();\n\nvar resolveSpawnOptions = function (nameOrOptions) {\n if (isString(nameOrOptions)) {\n return __assign(__assign({}, DEFAULT_SPAWN_OPTIONS), {\n name: nameOrOptions\n });\n }\n\n return __assign(__assign(__assign({}, DEFAULT_SPAWN_OPTIONS), {\n name: uniqueId()\n }), nameOrOptions);\n};\n\nfunction spawn(entity, nameOrOptions) {\n var resolvedOptions = resolveSpawnOptions(nameOrOptions);\n return consume(function (service) {\n if (!IS_PRODUCTION) {\n var isLazyEntity = isMachine(entity) || isFunction(entity);\n warn(!!service || isLazyEntity, \"Attempted to spawn an Actor (ID: \\\"\".concat(isMachine(entity) ? entity.id : 'undefined', \"\\\") outside of a service. This will have no effect.\"));\n }\n\n if (service) {\n return service.spawn(entity, resolvedOptions.name, resolvedOptions);\n } else {\n return createDeferredActor(entity, resolvedOptions.name);\n }\n });\n}\n/**\r\n * Creates a new Interpreter instance for the given machine with the provided options, if any.\r\n *\r\n * @param machine The machine to interpret\r\n * @param options Interpreter options\r\n */\n\nfunction interpret(machine, options) {\n var interpreter = new Interpreter(machine, options);\n return interpreter;\n}\n\nexport { Interpreter, InterpreterStatus, interpret, spawn };\n","import { __assign, __rest } from './_virtual/_tslib.js';\nimport './types.js';\nimport { invoke } from './actionTypes.js';\nimport './utils.js';\nimport './environment.js';\n\nfunction toInvokeSource(src) {\n if (typeof src === 'string') {\n var simpleSrc = {\n type: src\n };\n\n simpleSrc.toString = function () {\n return src;\n }; // v4 compat - TODO: remove in v5\n\n\n return simpleSrc;\n }\n\n return src;\n}\nfunction toInvokeDefinition(invokeConfig) {\n return __assign(__assign({\n type: invoke\n }, invokeConfig), {\n toJSON: function () {\n invokeConfig.onDone;\n invokeConfig.onError;\n var invokeDef = __rest(invokeConfig, [\"onDone\", \"onError\"]);\n\n return __assign(__assign({}, invokeDef), {\n type: invoke,\n src: toInvokeSource(invokeConfig.src)\n });\n }\n });\n}\n\nexport { toInvokeDefinition, toInvokeSource };\n","import { __assign, __spreadArray, __read, __values, __rest } from './_virtual/_tslib.js';\nimport { isFunction, mapValues, isArray, flatten, toArray, toStateValue, isString, getEventType, toSCXMLEvent, matchesState, path, evaluateGuard, mapContext, isRaisableAction, pathToStateValue, isBuiltInEvent, partition, updateHistoryValue, toStatePath, mapFilterValues, warn, toStatePaths, nestedPath, normalizeTarget, toGuard, toTransitionConfigArray, isMachine, createInvokeId } from './utils.js';\nimport { State, stateValuesEqual } from './State.js';\nimport { start as start$1, stop as stop$1, invoke, update, nullEvent } from './actionTypes.js';\nimport { done, start, toActionObjects, raise, stop, resolveActions, doneInvoke, error, toActionObject, toActivityDefinition, after, send, cancel, initEvent } from './actions.js';\nimport { IS_PRODUCTION } from './environment.js';\nimport { STATE_DELIMITER } from './constants.js';\nimport { getAllStateNodes, getConfiguration, isInFinalState, getTagsFromConfiguration, has, getChildren, getValue, isLeafNode, getAllChildren } from './stateUtils.js';\nimport { createInvocableActor } from './Actor.js';\nimport { toInvokeDefinition } from './invokeUtils.js';\n\nvar NULL_EVENT = '';\nvar STATE_IDENTIFIER = '#';\nvar WILDCARD = '*';\nvar EMPTY_OBJECT = {};\n\nvar isStateId = function (str) {\n return str[0] === STATE_IDENTIFIER;\n};\n\nvar createDefaultOptions = function () {\n return {\n actions: {},\n guards: {},\n services: {},\n activities: {},\n delays: {}\n };\n};\n\nvar validateArrayifiedTransitions = function (stateNode, event, transitions) {\n var hasNonLastUnguardedTarget = transitions.slice(0, -1).some(function (transition) {\n return !('cond' in transition) && !('in' in transition) && (isString(transition.target) || isMachine(transition.target));\n });\n var eventText = event === NULL_EVENT ? 'the transient event' : \"event '\".concat(event, \"'\");\n warn(!hasNonLastUnguardedTarget, \"One or more transitions for \".concat(eventText, \" on state '\").concat(stateNode.id, \"' are unreachable. \") + \"Make sure that the default transition is the last one defined.\");\n};\n\nvar StateNode =\n/*#__PURE__*/\n\n/** @class */\nfunction () {\n function StateNode(\n /**\r\n * The raw config used to create the machine.\r\n */\n config, options,\n /**\r\n * The initial extended state\r\n */\n _context, // TODO: this is unsafe, but we're removing it in v5 anyway\n _stateInfo) {\n if (_context === void 0) {\n _context = 'context' in config ? config.context : undefined;\n }\n\n var _this = this;\n\n var _a;\n\n this.config = config;\n this._context = _context;\n /**\r\n * The order this state node appears. Corresponds to the implicit SCXML document order.\r\n */\n\n this.order = -1;\n this.__xstatenode = true;\n this.__cache = {\n events: undefined,\n relativeValue: new Map(),\n initialStateValue: undefined,\n initialState: undefined,\n on: undefined,\n transitions: undefined,\n candidates: {},\n delayedTransitions: undefined\n };\n this.idMap = {};\n this.tags = [];\n this.options = Object.assign(createDefaultOptions(), options);\n this.parent = _stateInfo === null || _stateInfo === void 0 ? void 0 : _stateInfo.parent;\n this.key = this.config.key || (_stateInfo === null || _stateInfo === void 0 ? void 0 : _stateInfo.key) || this.config.id || '(machine)';\n this.machine = this.parent ? this.parent.machine : this;\n this.path = this.parent ? this.parent.path.concat(this.key) : [];\n this.delimiter = this.config.delimiter || (this.parent ? this.parent.delimiter : STATE_DELIMITER);\n this.id = this.config.id || __spreadArray([this.machine.key], __read(this.path), false).join(this.delimiter);\n this.version = this.parent ? this.parent.version : this.config.version;\n this.type = this.config.type || (this.config.parallel ? 'parallel' : this.config.states && Object.keys(this.config.states).length ? 'compound' : this.config.history ? 'history' : 'atomic');\n this.schema = this.parent ? this.machine.schema : (_a = this.config.schema) !== null && _a !== void 0 ? _a : {};\n this.description = this.config.description;\n\n if (!IS_PRODUCTION) {\n warn(!('parallel' in this.config), \"The \\\"parallel\\\" property is deprecated and will be removed in version 4.1. \".concat(this.config.parallel ? \"Replace with `type: 'parallel'`\" : \"Use `type: '\".concat(this.type, \"'`\"), \" in the config for state node '\").concat(this.id, \"' instead.\"));\n }\n\n this.initial = this.config.initial;\n this.states = this.config.states ? mapValues(this.config.states, function (stateConfig, key) {\n var _a;\n\n var stateNode = new StateNode(stateConfig, {}, undefined, {\n parent: _this,\n key: key\n });\n Object.assign(_this.idMap, __assign((_a = {}, _a[stateNode.id] = stateNode, _a), stateNode.idMap));\n return stateNode;\n }) : EMPTY_OBJECT; // Document order\n\n var order = 0;\n\n function dfs(stateNode) {\n var e_1, _a;\n\n stateNode.order = order++;\n\n try {\n for (var _b = __values(getAllChildren(stateNode)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var child = _c.value;\n dfs(child);\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n }\n\n dfs(this); // History config\n\n this.history = this.config.history === true ? 'shallow' : this.config.history || false;\n this._transient = !!this.config.always || (!this.config.on ? false : Array.isArray(this.config.on) ? this.config.on.some(function (_a) {\n var event = _a.event;\n return event === NULL_EVENT;\n }) : NULL_EVENT in this.config.on);\n this.strict = !!this.config.strict; // TODO: deprecate (entry)\n\n this.onEntry = toArray(this.config.entry || this.config.onEntry).map(function (action) {\n return toActionObject(action);\n }); // TODO: deprecate (exit)\n\n this.onExit = toArray(this.config.exit || this.config.onExit).map(function (action) {\n return toActionObject(action);\n });\n this.meta = this.config.meta;\n this.doneData = this.type === 'final' ? this.config.data : undefined;\n this.invoke = toArray(this.config.invoke).map(function (invokeConfig, i) {\n var _a, _b;\n\n if (isMachine(invokeConfig)) {\n var invokeId = createInvokeId(_this.id, i);\n _this.machine.options.services = __assign((_a = {}, _a[invokeId] = invokeConfig, _a), _this.machine.options.services);\n return toInvokeDefinition({\n src: invokeId,\n id: invokeId\n });\n } else if (isString(invokeConfig.src)) {\n var invokeId = invokeConfig.id || createInvokeId(_this.id, i);\n return toInvokeDefinition(__assign(__assign({}, invokeConfig), {\n id: invokeId,\n src: invokeConfig.src\n }));\n } else if (isMachine(invokeConfig.src) || isFunction(invokeConfig.src)) {\n var invokeId = invokeConfig.id || createInvokeId(_this.id, i);\n _this.machine.options.services = __assign((_b = {}, _b[invokeId] = invokeConfig.src, _b), _this.machine.options.services);\n return toInvokeDefinition(__assign(__assign({\n id: invokeId\n }, invokeConfig), {\n src: invokeId\n }));\n } else {\n var invokeSource = invokeConfig.src;\n return toInvokeDefinition(__assign(__assign({\n id: createInvokeId(_this.id, i)\n }, invokeConfig), {\n src: invokeSource\n }));\n }\n });\n this.activities = toArray(this.config.activities).concat(this.invoke).map(function (activity) {\n return toActivityDefinition(activity);\n });\n this.transition = this.transition.bind(this);\n this.tags = toArray(this.config.tags); // TODO: this is the real fix for initialization once\n // state node getters are deprecated\n // if (!this.parent) {\n // this._init();\n // }\n }\n\n StateNode.prototype._init = function () {\n if (this.__cache.transitions) {\n return;\n }\n\n getAllStateNodes(this).forEach(function (stateNode) {\n return stateNode.on;\n });\n };\n /**\r\n * Clones this state machine with custom options and context.\r\n *\r\n * @param options Options (actions, guards, activities, services) to recursively merge with the existing options.\r\n * @param context Custom context (will override predefined context)\r\n */\n\n\n StateNode.prototype.withConfig = function (options, context) {\n var _a = this.options,\n actions = _a.actions,\n activities = _a.activities,\n guards = _a.guards,\n services = _a.services,\n delays = _a.delays;\n return new StateNode(this.config, {\n actions: __assign(__assign({}, actions), options.actions),\n activities: __assign(__assign({}, activities), options.activities),\n guards: __assign(__assign({}, guards), options.guards),\n services: __assign(__assign({}, services), options.services),\n delays: __assign(__assign({}, delays), options.delays)\n }, context !== null && context !== void 0 ? context : this.context);\n };\n /**\r\n * Clones this state machine with custom context.\r\n *\r\n * @param context Custom context (will override predefined context, not recursive)\r\n */\n\n\n StateNode.prototype.withContext = function (context) {\n return new StateNode(this.config, this.options, context);\n };\n\n Object.defineProperty(StateNode.prototype, \"context\", {\n get: function () {\n return isFunction(this._context) ? this._context() : this._context;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"definition\", {\n /**\r\n * The well-structured state node definition.\r\n */\n get: function () {\n return {\n id: this.id,\n key: this.key,\n version: this.version,\n context: this.context,\n type: this.type,\n initial: this.initial,\n history: this.history,\n states: mapValues(this.states, function (state) {\n return state.definition;\n }),\n on: this.on,\n transitions: this.transitions,\n entry: this.onEntry,\n exit: this.onExit,\n activities: this.activities || [],\n meta: this.meta,\n order: this.order || -1,\n data: this.doneData,\n invoke: this.invoke,\n description: this.description,\n tags: this.tags\n };\n },\n enumerable: false,\n configurable: true\n });\n\n StateNode.prototype.toJSON = function () {\n return this.definition;\n };\n\n Object.defineProperty(StateNode.prototype, \"on\", {\n /**\r\n * The mapping of events to transitions.\r\n */\n get: function () {\n if (this.__cache.on) {\n return this.__cache.on;\n }\n\n var transitions = this.transitions;\n return this.__cache.on = transitions.reduce(function (map, transition) {\n map[transition.eventType] = map[transition.eventType] || [];\n map[transition.eventType].push(transition);\n return map;\n }, {});\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"after\", {\n get: function () {\n return this.__cache.delayedTransitions || (this.__cache.delayedTransitions = this.getDelayedTransitions(), this.__cache.delayedTransitions);\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"transitions\", {\n /**\r\n * All the transitions that can be taken from this state node.\r\n */\n get: function () {\n return this.__cache.transitions || (this.__cache.transitions = this.formatTransitions(), this.__cache.transitions);\n },\n enumerable: false,\n configurable: true\n });\n\n StateNode.prototype.getCandidates = function (eventName) {\n if (this.__cache.candidates[eventName]) {\n return this.__cache.candidates[eventName];\n }\n\n var transient = eventName === NULL_EVENT;\n var candidates = this.transitions.filter(function (transition) {\n var sameEventType = transition.eventType === eventName; // null events should only match against eventless transitions\n\n return transient ? sameEventType : sameEventType || transition.eventType === WILDCARD;\n });\n this.__cache.candidates[eventName] = candidates;\n return candidates;\n };\n /**\r\n * All delayed transitions from the config.\r\n */\n\n\n StateNode.prototype.getDelayedTransitions = function () {\n var _this = this;\n\n var afterConfig = this.config.after;\n\n if (!afterConfig) {\n return [];\n }\n\n var mutateEntryExit = function (delay, i) {\n var delayRef = isFunction(delay) ? \"\".concat(_this.id, \":delay[\").concat(i, \"]\") : delay;\n var eventType = after(delayRef, _this.id);\n\n _this.onEntry.push(send(eventType, {\n delay: delay\n }));\n\n _this.onExit.push(cancel(eventType));\n\n return eventType;\n };\n\n var delayedTransitions = isArray(afterConfig) ? afterConfig.map(function (transition, i) {\n var eventType = mutateEntryExit(transition.delay, i);\n return __assign(__assign({}, transition), {\n event: eventType\n });\n }) : flatten(Object.keys(afterConfig).map(function (delay, i) {\n var configTransition = afterConfig[delay];\n var resolvedTransition = isString(configTransition) ? {\n target: configTransition\n } : configTransition;\n var resolvedDelay = !isNaN(+delay) ? +delay : delay;\n var eventType = mutateEntryExit(resolvedDelay, i);\n return toArray(resolvedTransition).map(function (transition) {\n return __assign(__assign({}, transition), {\n event: eventType,\n delay: resolvedDelay\n });\n });\n }));\n return delayedTransitions.map(function (delayedTransition) {\n var delay = delayedTransition.delay;\n return __assign(__assign({}, _this.formatTransition(delayedTransition)), {\n delay: delay\n });\n });\n };\n /**\r\n * Returns the state nodes represented by the current state value.\r\n *\r\n * @param state The state value or State instance\r\n */\n\n\n StateNode.prototype.getStateNodes = function (state) {\n var _a;\n\n var _this = this;\n\n if (!state) {\n return [];\n }\n\n var stateValue = state instanceof State ? state.value : toStateValue(state, this.delimiter);\n\n if (isString(stateValue)) {\n var initialStateValue = this.getStateNode(stateValue).initial;\n return initialStateValue !== undefined ? this.getStateNodes((_a = {}, _a[stateValue] = initialStateValue, _a)) : [this, this.states[stateValue]];\n }\n\n var subStateKeys = Object.keys(stateValue);\n var subStateNodes = [this];\n subStateNodes.push.apply(subStateNodes, __spreadArray([], __read(flatten(subStateKeys.map(function (subStateKey) {\n return _this.getStateNode(subStateKey).getStateNodes(stateValue[subStateKey]);\n }))), false));\n return subStateNodes;\n };\n /**\r\n * Returns `true` if this state node explicitly handles the given event.\r\n *\r\n * @param event The event in question\r\n */\n\n\n StateNode.prototype.handles = function (event) {\n var eventType = getEventType(event);\n return this.events.includes(eventType);\n };\n /**\r\n * Resolves the given `state` to a new `State` instance relative to this machine.\r\n *\r\n * This ensures that `.events` and `.nextEvents` represent the correct values.\r\n *\r\n * @param state The state to resolve\r\n */\n\n\n StateNode.prototype.resolveState = function (state) {\n var stateFromConfig = state instanceof State ? state : State.create(state);\n var configuration = Array.from(getConfiguration([], this.getStateNodes(stateFromConfig.value)));\n return new State(__assign(__assign({}, stateFromConfig), {\n value: this.resolve(stateFromConfig.value),\n configuration: configuration,\n done: isInFinalState(configuration, this),\n tags: getTagsFromConfiguration(configuration),\n machine: this.machine\n }));\n };\n\n StateNode.prototype.transitionLeafNode = function (stateValue, state, _event) {\n var stateNode = this.getStateNode(stateValue);\n var next = stateNode.next(state, _event);\n\n if (!next || !next.transitions.length) {\n return this.next(state, _event);\n }\n\n return next;\n };\n\n StateNode.prototype.transitionCompoundNode = function (stateValue, state, _event) {\n var subStateKeys = Object.keys(stateValue);\n var stateNode = this.getStateNode(subStateKeys[0]);\n\n var next = stateNode._transition(stateValue[subStateKeys[0]], state, _event);\n\n if (!next || !next.transitions.length) {\n return this.next(state, _event);\n }\n\n return next;\n };\n\n StateNode.prototype.transitionParallelNode = function (stateValue, state, _event) {\n var e_2, _a;\n\n var transitionMap = {};\n\n try {\n for (var _b = __values(Object.keys(stateValue)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var subStateKey = _c.value;\n var subStateValue = stateValue[subStateKey];\n\n if (!subStateValue) {\n continue;\n }\n\n var subStateNode = this.getStateNode(subStateKey);\n\n var next = subStateNode._transition(subStateValue, state, _event);\n\n if (next) {\n transitionMap[subStateKey] = next;\n }\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n\n var stateTransitions = Object.keys(transitionMap).map(function (key) {\n return transitionMap[key];\n });\n var enabledTransitions = flatten(stateTransitions.map(function (st) {\n return st.transitions;\n }));\n var willTransition = stateTransitions.some(function (st) {\n return st.transitions.length > 0;\n });\n\n if (!willTransition) {\n return this.next(state, _event);\n }\n\n var configuration = flatten(Object.keys(transitionMap).map(function (key) {\n return transitionMap[key].configuration;\n }));\n return {\n transitions: enabledTransitions,\n exitSet: flatten(stateTransitions.map(function (t) {\n return t.exitSet;\n })),\n configuration: configuration,\n source: state,\n actions: flatten(Object.keys(transitionMap).map(function (key) {\n return transitionMap[key].actions;\n }))\n };\n };\n\n StateNode.prototype._transition = function (stateValue, state, _event) {\n // leaf node\n if (isString(stateValue)) {\n return this.transitionLeafNode(stateValue, state, _event);\n } // hierarchical node\n\n\n if (Object.keys(stateValue).length === 1) {\n return this.transitionCompoundNode(stateValue, state, _event);\n } // orthogonal node\n\n\n return this.transitionParallelNode(stateValue, state, _event);\n };\n\n StateNode.prototype.getTransitionData = function (state, event) {\n return this._transition(state.value, state, toSCXMLEvent(event));\n };\n\n StateNode.prototype.next = function (state, _event) {\n var e_3, _a;\n\n var _this = this;\n\n var eventName = _event.name;\n var actions = [];\n var nextStateNodes = [];\n var selectedTransition;\n\n try {\n for (var _b = __values(this.getCandidates(eventName)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var candidate = _c.value;\n var cond = candidate.cond,\n stateIn = candidate.in;\n var resolvedContext = state.context;\n var isInState = stateIn ? isString(stateIn) && isStateId(stateIn) ? // Check if in state by ID\n state.matches(toStateValue(this.getStateNodeById(stateIn).path, this.delimiter)) : // Check if in state by relative grandparent\n matchesState(toStateValue(stateIn, this.delimiter), path(this.path.slice(0, -2))(state.value)) : true;\n var guardPassed = false;\n\n try {\n guardPassed = !cond || evaluateGuard(this.machine, cond, resolvedContext, _event, state);\n } catch (err) {\n throw new Error(\"Unable to evaluate guard '\".concat(cond.name || cond.type, \"' in transition for event '\").concat(eventName, \"' in state node '\").concat(this.id, \"':\\n\").concat(err.message));\n }\n\n if (guardPassed && isInState) {\n if (candidate.target !== undefined) {\n nextStateNodes = candidate.target;\n }\n\n actions.push.apply(actions, __spreadArray([], __read(candidate.actions), false));\n selectedTransition = candidate;\n break;\n }\n }\n } catch (e_3_1) {\n e_3 = {\n error: e_3_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_3) throw e_3.error;\n }\n }\n\n if (!selectedTransition) {\n return undefined;\n }\n\n if (!nextStateNodes.length) {\n return {\n transitions: [selectedTransition],\n exitSet: [],\n configuration: state.value ? [this] : [],\n source: state,\n actions: actions\n };\n }\n\n var allNextStateNodes = flatten(nextStateNodes.map(function (stateNode) {\n return _this.getRelativeStateNodes(stateNode, state.historyValue);\n }));\n var isInternal = !!selectedTransition.internal;\n return {\n transitions: [selectedTransition],\n exitSet: isInternal ? [] : flatten(nextStateNodes.map(function (targetNode) {\n return _this.getPotentiallyReenteringNodes(targetNode);\n })),\n configuration: allNextStateNodes,\n source: state,\n actions: actions\n };\n }; // even though the name of this function mentions reentry nodes\n // we are pushing its result into `exitSet`\n // that's because what we exit might be reentered (it's an invariant of reentrancy)\n\n\n StateNode.prototype.getPotentiallyReenteringNodes = function (targetNode) {\n if (this.order < targetNode.order) {\n return [this];\n }\n\n var nodes = [];\n var marker = this;\n var possibleAncestor = targetNode;\n\n while (marker && marker !== possibleAncestor) {\n nodes.push(marker);\n marker = marker.parent;\n }\n\n if (marker !== possibleAncestor) {\n // we never got to `possibleAncestor`, therefore the initial `marker` \"escapes\" it\n // it's in a different part of the tree so no states will be reentered for such an external transition\n return [];\n }\n\n nodes.push(possibleAncestor);\n return nodes;\n };\n\n StateNode.prototype.getActions = function (resolvedConfig, isDone, transition, currentContext, _event, prevState, predictableExec) {\n var e_4, _a, e_5, _b;\n\n var _this = this;\n\n var prevConfig = prevState ? getConfiguration([], this.getStateNodes(prevState.value)) : [];\n var entrySet = new Set();\n\n try {\n for (var _c = __values(Array.from(resolvedConfig).sort(function (a, b) {\n return a.order - b.order;\n })), _d = _c.next(); !_d.done; _d = _c.next()) {\n var sn = _d.value;\n\n if (!has(prevConfig, sn) || has(transition.exitSet, sn) || sn.parent && entrySet.has(sn.parent)) {\n entrySet.add(sn);\n }\n }\n } catch (e_4_1) {\n e_4 = {\n error: e_4_1\n };\n } finally {\n try {\n if (_d && !_d.done && (_a = _c.return)) _a.call(_c);\n } finally {\n if (e_4) throw e_4.error;\n }\n }\n\n try {\n for (var prevConfig_1 = __values(prevConfig), prevConfig_1_1 = prevConfig_1.next(); !prevConfig_1_1.done; prevConfig_1_1 = prevConfig_1.next()) {\n var sn = prevConfig_1_1.value;\n\n if (!has(resolvedConfig, sn) || has(transition.exitSet, sn.parent)) {\n transition.exitSet.push(sn);\n }\n }\n } catch (e_5_1) {\n e_5 = {\n error: e_5_1\n };\n } finally {\n try {\n if (prevConfig_1_1 && !prevConfig_1_1.done && (_b = prevConfig_1.return)) _b.call(prevConfig_1);\n } finally {\n if (e_5) throw e_5.error;\n }\n }\n\n transition.exitSet.sort(function (a, b) {\n return b.order - a.order;\n });\n var entryStates = Array.from(entrySet).sort(function (a, b) {\n return a.order - b.order;\n });\n var exitStates = new Set(transition.exitSet);\n var doneEvents = flatten(entryStates.map(function (sn) {\n var events = [];\n\n if (sn.type !== 'final') {\n return events;\n }\n\n var parent = sn.parent;\n\n if (!parent.parent) {\n return events;\n }\n\n events.push(done(sn.id, sn.doneData), // TODO: deprecate - final states should not emit done events for their own state.\n done(parent.id, sn.doneData ? mapContext(sn.doneData, currentContext, _event) : undefined));\n var grandparent = parent.parent;\n\n if (grandparent.type === 'parallel') {\n if (getChildren(grandparent).every(function (parentNode) {\n return isInFinalState(transition.configuration, parentNode);\n })) {\n events.push(done(grandparent.id));\n }\n }\n\n return events;\n }));\n var entryActions = entryStates.map(function (stateNode) {\n var entryActions = stateNode.onEntry;\n var invokeActions = stateNode.activities.map(function (activity) {\n return start(activity);\n });\n return {\n type: 'entry',\n actions: toActionObjects(predictableExec ? __spreadArray(__spreadArray([], __read(entryActions), false), __read(invokeActions), false) : __spreadArray(__spreadArray([], __read(invokeActions), false), __read(entryActions), false), _this.machine.options.actions)\n };\n }).concat({\n type: 'state_done',\n actions: doneEvents.map(function (event) {\n return raise(event);\n })\n });\n var exitActions = Array.from(exitStates).map(function (stateNode) {\n return {\n type: 'exit',\n actions: toActionObjects(__spreadArray(__spreadArray([], __read(stateNode.onExit), false), __read(stateNode.activities.map(function (activity) {\n return stop(activity);\n })), false), _this.machine.options.actions)\n };\n });\n var actions = exitActions.concat({\n type: 'transition',\n actions: toActionObjects(transition.actions, this.machine.options.actions)\n }).concat(entryActions);\n\n if (isDone) {\n var stopActions = toActionObjects(flatten(__spreadArray([], __read(resolvedConfig), false).sort(function (a, b) {\n return b.order - a.order;\n }).map(function (stateNode) {\n return stateNode.onExit;\n })), this.machine.options.actions).filter(function (action) {\n return !isRaisableAction(action);\n });\n return actions.concat({\n type: 'stop',\n actions: stopActions\n });\n }\n\n return actions;\n };\n /**\r\n * Determines the next state given the current `state` and sent `event`.\r\n *\r\n * @param state The current State instance or state value\r\n * @param event The event that was sent at the current state\r\n * @param context The current context (extended state) of the current state\r\n */\n\n\n StateNode.prototype.transition = function (state, event, context, exec) {\n if (state === void 0) {\n state = this.initialState;\n }\n\n var _event = toSCXMLEvent(event);\n\n var currentState;\n\n if (state instanceof State) {\n currentState = context === undefined ? state : this.resolveState(State.from(state, context));\n } else {\n var resolvedStateValue = isString(state) ? this.resolve(pathToStateValue(this.getResolvedPath(state))) : this.resolve(state);\n var resolvedContext = context !== null && context !== void 0 ? context : this.machine.context;\n currentState = this.resolveState(State.from(resolvedStateValue, resolvedContext));\n }\n\n if (!IS_PRODUCTION && _event.name === WILDCARD) {\n throw new Error(\"An event cannot have the wildcard type ('\".concat(WILDCARD, \"')\"));\n }\n\n if (this.strict) {\n if (!this.events.includes(_event.name) && !isBuiltInEvent(_event.name)) {\n throw new Error(\"Machine '\".concat(this.id, \"' does not accept event '\").concat(_event.name, \"'\"));\n }\n }\n\n var stateTransition = this._transition(currentState.value, currentState, _event) || {\n transitions: [],\n configuration: [],\n exitSet: [],\n source: currentState,\n actions: []\n };\n var prevConfig = getConfiguration([], this.getStateNodes(currentState.value));\n var resolvedConfig = stateTransition.configuration.length ? getConfiguration(prevConfig, stateTransition.configuration) : prevConfig;\n stateTransition.configuration = __spreadArray([], __read(resolvedConfig), false);\n return this.resolveTransition(stateTransition, currentState, currentState.context, exec, _event);\n };\n\n StateNode.prototype.resolveRaisedTransition = function (state, _event, originalEvent, predictableExec) {\n var _a;\n\n var currentActions = state.actions;\n state = this.transition(state, _event, undefined, predictableExec); // Save original event to state\n // TODO: this should be the raised event! Delete in V5 (breaking)\n\n state._event = originalEvent;\n state.event = originalEvent.data;\n\n (_a = state.actions).unshift.apply(_a, __spreadArray([], __read(currentActions), false));\n\n return state;\n };\n\n StateNode.prototype.resolveTransition = function (stateTransition, currentState, context, predictableExec, _event) {\n var e_6, _a, e_7, _b;\n\n var _this = this;\n\n if (_event === void 0) {\n _event = initEvent;\n }\n\n var configuration = stateTransition.configuration; // Transition will \"apply\" if:\n // - this is the initial state (there is no current state)\n // - OR there are transitions\n\n var willTransition = !currentState || stateTransition.transitions.length > 0;\n var resolvedConfiguration = willTransition ? stateTransition.configuration : currentState ? currentState.configuration : [];\n var isDone = isInFinalState(resolvedConfiguration, this);\n var resolvedStateValue = willTransition ? getValue(this.machine, configuration) : undefined;\n var historyValue = currentState ? currentState.historyValue ? currentState.historyValue : stateTransition.source ? this.machine.historyValue(currentState.value) : undefined : undefined;\n var actionBlocks = this.getActions(new Set(resolvedConfiguration), isDone, stateTransition, context, _event, currentState, predictableExec);\n var activities = currentState ? __assign({}, currentState.activities) : {};\n\n try {\n for (var actionBlocks_1 = __values(actionBlocks), actionBlocks_1_1 = actionBlocks_1.next(); !actionBlocks_1_1.done; actionBlocks_1_1 = actionBlocks_1.next()) {\n var block = actionBlocks_1_1.value;\n\n try {\n for (var _c = (e_7 = void 0, __values(block.actions)), _d = _c.next(); !_d.done; _d = _c.next()) {\n var action = _d.value;\n\n if (action.type === start$1) {\n activities[action.activity.id || action.activity.type] = action;\n } else if (action.type === stop$1) {\n activities[action.activity.id || action.activity.type] = false;\n }\n }\n } catch (e_7_1) {\n e_7 = {\n error: e_7_1\n };\n } finally {\n try {\n if (_d && !_d.done && (_b = _c.return)) _b.call(_c);\n } finally {\n if (e_7) throw e_7.error;\n }\n }\n }\n } catch (e_6_1) {\n e_6 = {\n error: e_6_1\n };\n } finally {\n try {\n if (actionBlocks_1_1 && !actionBlocks_1_1.done && (_a = actionBlocks_1.return)) _a.call(actionBlocks_1);\n } finally {\n if (e_6) throw e_6.error;\n }\n }\n\n var _e = __read(resolveActions(this, currentState, context, _event, actionBlocks, predictableExec, this.machine.config.predictableActionArguments || this.machine.config.preserveActionOrder), 2),\n resolvedActions = _e[0],\n updatedContext = _e[1];\n\n var _f = __read(partition(resolvedActions, isRaisableAction), 2),\n raisedEvents = _f[0],\n nonRaisedActions = _f[1];\n\n var invokeActions = resolvedActions.filter(function (action) {\n var _a;\n\n return action.type === start$1 && ((_a = action.activity) === null || _a === void 0 ? void 0 : _a.type) === invoke;\n });\n var children = invokeActions.reduce(function (acc, action) {\n acc[action.activity.id] = createInvocableActor(action.activity, _this.machine, updatedContext, _event);\n return acc;\n }, currentState ? __assign({}, currentState.children) : {});\n var nextState = new State({\n value: resolvedStateValue || currentState.value,\n context: updatedContext,\n _event: _event,\n // Persist _sessionid between states\n _sessionid: currentState ? currentState._sessionid : null,\n historyValue: resolvedStateValue ? historyValue ? updateHistoryValue(historyValue, resolvedStateValue) : undefined : currentState ? currentState.historyValue : undefined,\n history: !resolvedStateValue || stateTransition.source ? currentState : undefined,\n actions: resolvedStateValue ? nonRaisedActions : [],\n activities: resolvedStateValue ? activities : currentState ? currentState.activities : {},\n events: [],\n configuration: resolvedConfiguration,\n transitions: stateTransition.transitions,\n children: children,\n done: isDone,\n tags: getTagsFromConfiguration(resolvedConfiguration),\n machine: this\n });\n var didUpdateContext = context !== updatedContext;\n nextState.changed = _event.name === update || didUpdateContext; // Dispose of penultimate histories to prevent memory leaks\n\n var history = nextState.history;\n\n if (history) {\n delete history.history;\n } // There are transient transitions if the machine is not in a final state\n // and if some of the state nodes have transient (\"always\") transitions.\n\n\n var hasAlwaysTransitions = !isDone && (this._transient || configuration.some(function (stateNode) {\n return stateNode._transient;\n })); // If there are no enabled transitions, check if there are transient transitions.\n // If there are transient transitions, continue checking for more transitions\n // because an transient transition should be triggered even if there are no\n // enabled transitions.\n //\n // If we're already working on an transient transition then stop to prevent an infinite loop.\n //\n // Otherwise, if there are no enabled nor transient transitions, we are done.\n\n if (!willTransition && (!hasAlwaysTransitions || _event.name === NULL_EVENT)) {\n return nextState;\n }\n\n var maybeNextState = nextState;\n\n if (!isDone) {\n if (hasAlwaysTransitions) {\n maybeNextState = this.resolveRaisedTransition(maybeNextState, {\n type: nullEvent\n }, _event, predictableExec);\n }\n\n while (raisedEvents.length) {\n var raisedEvent = raisedEvents.shift();\n maybeNextState = this.resolveRaisedTransition(maybeNextState, raisedEvent._event, _event, predictableExec);\n }\n } // Detect if state changed\n\n\n var changed = maybeNextState.changed || (history ? !!maybeNextState.actions.length || didUpdateContext || typeof history.value !== typeof maybeNextState.value || !stateValuesEqual(maybeNextState.value, history.value) : undefined);\n maybeNextState.changed = changed; // Preserve original history after raised events\n\n maybeNextState.history = history;\n return maybeNextState;\n };\n /**\r\n * Returns the child state node from its relative `stateKey`, or throws.\r\n */\n\n\n StateNode.prototype.getStateNode = function (stateKey) {\n if (isStateId(stateKey)) {\n return this.machine.getStateNodeById(stateKey);\n }\n\n if (!this.states) {\n throw new Error(\"Unable to retrieve child state '\".concat(stateKey, \"' from '\").concat(this.id, \"'; no child states exist.\"));\n }\n\n var result = this.states[stateKey];\n\n if (!result) {\n throw new Error(\"Child state '\".concat(stateKey, \"' does not exist on '\").concat(this.id, \"'\"));\n }\n\n return result;\n };\n /**\r\n * Returns the state node with the given `stateId`, or throws.\r\n *\r\n * @param stateId The state ID. The prefix \"#\" is removed.\r\n */\n\n\n StateNode.prototype.getStateNodeById = function (stateId) {\n var resolvedStateId = isStateId(stateId) ? stateId.slice(STATE_IDENTIFIER.length) : stateId;\n\n if (resolvedStateId === this.id) {\n return this;\n }\n\n var stateNode = this.machine.idMap[resolvedStateId];\n\n if (!stateNode) {\n throw new Error(\"Child state node '#\".concat(resolvedStateId, \"' does not exist on machine '\").concat(this.id, \"'\"));\n }\n\n return stateNode;\n };\n /**\r\n * Returns the relative state node from the given `statePath`, or throws.\r\n *\r\n * @param statePath The string or string array relative path to the state node.\r\n */\n\n\n StateNode.prototype.getStateNodeByPath = function (statePath) {\n if (typeof statePath === 'string' && isStateId(statePath)) {\n try {\n return this.getStateNodeById(statePath.slice(1));\n } catch (e) {// try individual paths\n // throw e;\n }\n }\n\n var arrayStatePath = toStatePath(statePath, this.delimiter).slice();\n var currentStateNode = this;\n\n while (arrayStatePath.length) {\n var key = arrayStatePath.shift();\n\n if (!key.length) {\n break;\n }\n\n currentStateNode = currentStateNode.getStateNode(key);\n }\n\n return currentStateNode;\n };\n /**\r\n * Resolves a partial state value with its full representation in this machine.\r\n *\r\n * @param stateValue The partial state value to resolve.\r\n */\n\n\n StateNode.prototype.resolve = function (stateValue) {\n var _a;\n\n var _this = this;\n\n if (!stateValue) {\n return this.initialStateValue || EMPTY_OBJECT; // TODO: type-specific properties\n }\n\n switch (this.type) {\n case 'parallel':\n return mapValues(this.initialStateValue, function (subStateValue, subStateKey) {\n return subStateValue ? _this.getStateNode(subStateKey).resolve(stateValue[subStateKey] || subStateValue) : EMPTY_OBJECT;\n });\n\n case 'compound':\n if (isString(stateValue)) {\n var subStateNode = this.getStateNode(stateValue);\n\n if (subStateNode.type === 'parallel' || subStateNode.type === 'compound') {\n return _a = {}, _a[stateValue] = subStateNode.initialStateValue, _a;\n }\n\n return stateValue;\n }\n\n if (!Object.keys(stateValue).length) {\n return this.initialStateValue || {};\n }\n\n return mapValues(stateValue, function (subStateValue, subStateKey) {\n return subStateValue ? _this.getStateNode(subStateKey).resolve(subStateValue) : EMPTY_OBJECT;\n });\n\n default:\n return stateValue || EMPTY_OBJECT;\n }\n };\n\n StateNode.prototype.getResolvedPath = function (stateIdentifier) {\n if (isStateId(stateIdentifier)) {\n var stateNode = this.machine.idMap[stateIdentifier.slice(STATE_IDENTIFIER.length)];\n\n if (!stateNode) {\n throw new Error(\"Unable to find state node '\".concat(stateIdentifier, \"'\"));\n }\n\n return stateNode.path;\n }\n\n return toStatePath(stateIdentifier, this.delimiter);\n };\n\n Object.defineProperty(StateNode.prototype, \"initialStateValue\", {\n get: function () {\n var _a;\n\n if (this.__cache.initialStateValue) {\n return this.__cache.initialStateValue;\n }\n\n var initialStateValue;\n\n if (this.type === 'parallel') {\n initialStateValue = mapFilterValues(this.states, function (state) {\n return state.initialStateValue || EMPTY_OBJECT;\n }, function (stateNode) {\n return !(stateNode.type === 'history');\n });\n } else if (this.initial !== undefined) {\n if (!this.states[this.initial]) {\n throw new Error(\"Initial state '\".concat(this.initial, \"' not found on '\").concat(this.key, \"'\"));\n }\n\n initialStateValue = isLeafNode(this.states[this.initial]) ? this.initial : (_a = {}, _a[this.initial] = this.states[this.initial].initialStateValue, _a);\n } else {\n // The finite state value of a machine without child states is just an empty object\n initialStateValue = {};\n }\n\n this.__cache.initialStateValue = initialStateValue;\n return this.__cache.initialStateValue;\n },\n enumerable: false,\n configurable: true\n });\n\n StateNode.prototype.getInitialState = function (stateValue, context) {\n this._init(); // TODO: this should be in the constructor (see note in constructor)\n\n\n var configuration = this.getStateNodes(stateValue);\n return this.resolveTransition({\n configuration: configuration,\n exitSet: [],\n transitions: [],\n source: undefined,\n actions: []\n }, undefined, context !== null && context !== void 0 ? context : this.machine.context, undefined);\n };\n\n Object.defineProperty(StateNode.prototype, \"initialState\", {\n /**\r\n * The initial State instance, which includes all actions to be executed from\r\n * entering the initial state.\r\n */\n get: function () {\n var initialStateValue = this.initialStateValue;\n\n if (!initialStateValue) {\n throw new Error(\"Cannot retrieve initial state from simple state '\".concat(this.id, \"'.\"));\n }\n\n return this.getInitialState(initialStateValue);\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"target\", {\n /**\r\n * The target state value of the history state node, if it exists. This represents the\r\n * default state value to transition to if no history value exists yet.\r\n */\n get: function () {\n var target;\n\n if (this.type === 'history') {\n var historyConfig = this.config;\n\n if (isString(historyConfig.target)) {\n target = isStateId(historyConfig.target) ? pathToStateValue(this.machine.getStateNodeById(historyConfig.target).path.slice(this.path.length - 1)) : historyConfig.target;\n } else {\n target = historyConfig.target;\n }\n }\n\n return target;\n },\n enumerable: false,\n configurable: true\n });\n /**\r\n * Returns the leaf nodes from a state path relative to this state node.\r\n *\r\n * @param relativeStateId The relative state path to retrieve the state nodes\r\n * @param history The previous state to retrieve history\r\n * @param resolve Whether state nodes should resolve to initial child state nodes\r\n */\n\n StateNode.prototype.getRelativeStateNodes = function (relativeStateId, historyValue, resolve) {\n if (resolve === void 0) {\n resolve = true;\n }\n\n return resolve ? relativeStateId.type === 'history' ? relativeStateId.resolveHistory(historyValue) : relativeStateId.initialStateNodes : [relativeStateId];\n };\n\n Object.defineProperty(StateNode.prototype, \"initialStateNodes\", {\n get: function () {\n var _this = this;\n\n if (isLeafNode(this)) {\n return [this];\n } // Case when state node is compound but no initial state is defined\n\n\n if (this.type === 'compound' && !this.initial) {\n if (!IS_PRODUCTION) {\n warn(false, \"Compound state node '\".concat(this.id, \"' has no initial state.\"));\n }\n\n return [this];\n }\n\n var initialStateNodePaths = toStatePaths(this.initialStateValue);\n return flatten(initialStateNodePaths.map(function (initialPath) {\n return _this.getFromRelativePath(initialPath);\n }));\n },\n enumerable: false,\n configurable: true\n });\n /**\r\n * Retrieves state nodes from a relative path to this state node.\r\n *\r\n * @param relativePath The relative path from this state node\r\n * @param historyValue\r\n */\n\n StateNode.prototype.getFromRelativePath = function (relativePath) {\n if (!relativePath.length) {\n return [this];\n }\n\n var _a = __read(relativePath),\n stateKey = _a[0],\n childStatePath = _a.slice(1);\n\n if (!this.states) {\n throw new Error(\"Cannot retrieve subPath '\".concat(stateKey, \"' from node with no states\"));\n }\n\n var childStateNode = this.getStateNode(stateKey);\n\n if (childStateNode.type === 'history') {\n return childStateNode.resolveHistory();\n }\n\n if (!this.states[stateKey]) {\n throw new Error(\"Child state '\".concat(stateKey, \"' does not exist on '\").concat(this.id, \"'\"));\n }\n\n return this.states[stateKey].getFromRelativePath(childStatePath);\n };\n\n StateNode.prototype.historyValue = function (relativeStateValue) {\n if (!Object.keys(this.states).length) {\n return undefined;\n }\n\n return {\n current: relativeStateValue || this.initialStateValue,\n states: mapFilterValues(this.states, function (stateNode, key) {\n if (!relativeStateValue) {\n return stateNode.historyValue();\n }\n\n var subStateValue = isString(relativeStateValue) ? undefined : relativeStateValue[key];\n return stateNode.historyValue(subStateValue || stateNode.initialStateValue);\n }, function (stateNode) {\n return !stateNode.history;\n })\n };\n };\n /**\r\n * Resolves to the historical value(s) of the parent state node,\r\n * represented by state nodes.\r\n *\r\n * @param historyValue\r\n */\n\n\n StateNode.prototype.resolveHistory = function (historyValue) {\n var _this = this;\n\n if (this.type !== 'history') {\n return [this];\n }\n\n var parent = this.parent;\n\n if (!historyValue) {\n var historyTarget = this.target;\n return historyTarget ? flatten(toStatePaths(historyTarget).map(function (relativeChildPath) {\n return parent.getFromRelativePath(relativeChildPath);\n })) : parent.initialStateNodes;\n }\n\n var subHistoryValue = nestedPath(parent.path, 'states')(historyValue).current;\n\n if (isString(subHistoryValue)) {\n return [parent.getStateNode(subHistoryValue)];\n }\n\n return flatten(toStatePaths(subHistoryValue).map(function (subStatePath) {\n return _this.history === 'deep' ? parent.getFromRelativePath(subStatePath) : [parent.states[subStatePath[0]]];\n }));\n };\n\n Object.defineProperty(StateNode.prototype, \"stateIds\", {\n /**\r\n * All the state node IDs of this state node and its descendant state nodes.\r\n */\n get: function () {\n var _this = this;\n\n var childStateIds = flatten(Object.keys(this.states).map(function (stateKey) {\n return _this.states[stateKey].stateIds;\n }));\n return [this.id].concat(childStateIds);\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"events\", {\n /**\r\n * All the event types accepted by this state node and its descendants.\r\n */\n get: function () {\n var e_8, _a, e_9, _b;\n\n if (this.__cache.events) {\n return this.__cache.events;\n }\n\n var states = this.states;\n var events = new Set(this.ownEvents);\n\n if (states) {\n try {\n for (var _c = __values(Object.keys(states)), _d = _c.next(); !_d.done; _d = _c.next()) {\n var stateId = _d.value;\n var state = states[stateId];\n\n if (state.states) {\n try {\n for (var _e = (e_9 = void 0, __values(state.events)), _f = _e.next(); !_f.done; _f = _e.next()) {\n var event_1 = _f.value;\n events.add(\"\".concat(event_1));\n }\n } catch (e_9_1) {\n e_9 = {\n error: e_9_1\n };\n } finally {\n try {\n if (_f && !_f.done && (_b = _e.return)) _b.call(_e);\n } finally {\n if (e_9) throw e_9.error;\n }\n }\n }\n }\n } catch (e_8_1) {\n e_8 = {\n error: e_8_1\n };\n } finally {\n try {\n if (_d && !_d.done && (_a = _c.return)) _a.call(_c);\n } finally {\n if (e_8) throw e_8.error;\n }\n }\n }\n\n return this.__cache.events = Array.from(events);\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"ownEvents\", {\n /**\r\n * All the events that have transitions directly from this state node.\r\n *\r\n * Excludes any inert events.\r\n */\n get: function () {\n var events = new Set(this.transitions.filter(function (transition) {\n return !(!transition.target && !transition.actions.length && transition.internal);\n }).map(function (transition) {\n return transition.eventType;\n }));\n return Array.from(events);\n },\n enumerable: false,\n configurable: true\n });\n\n StateNode.prototype.resolveTarget = function (_target) {\n var _this = this;\n\n if (_target === undefined) {\n // an undefined target signals that the state node should not transition from that state when receiving that event\n return undefined;\n }\n\n return _target.map(function (target) {\n if (!isString(target)) {\n return target;\n }\n\n var isInternalTarget = target[0] === _this.delimiter; // If internal target is defined on machine,\n // do not include machine key on target\n\n if (isInternalTarget && !_this.parent) {\n return _this.getStateNodeByPath(target.slice(1));\n }\n\n var resolvedTarget = isInternalTarget ? _this.key + target : target;\n\n if (_this.parent) {\n try {\n var targetStateNode = _this.parent.getStateNodeByPath(resolvedTarget);\n\n return targetStateNode;\n } catch (err) {\n throw new Error(\"Invalid transition definition for state node '\".concat(_this.id, \"':\\n\").concat(err.message));\n }\n } else {\n return _this.getStateNodeByPath(resolvedTarget);\n }\n });\n };\n\n StateNode.prototype.formatTransition = function (transitionConfig) {\n var _this = this;\n\n var normalizedTarget = normalizeTarget(transitionConfig.target);\n var internal = 'internal' in transitionConfig ? transitionConfig.internal : normalizedTarget ? normalizedTarget.some(function (_target) {\n return isString(_target) && _target[0] === _this.delimiter;\n }) : true;\n var guards = this.machine.options.guards;\n var target = this.resolveTarget(normalizedTarget);\n\n var transition = __assign(__assign({}, transitionConfig), {\n actions: toActionObjects(toArray(transitionConfig.actions)),\n cond: toGuard(transitionConfig.cond, guards),\n target: target,\n source: this,\n internal: internal,\n eventType: transitionConfig.event,\n toJSON: function () {\n return __assign(__assign({}, transition), {\n target: transition.target ? transition.target.map(function (t) {\n return \"#\".concat(t.id);\n }) : undefined,\n source: \"#\".concat(_this.id)\n });\n }\n });\n\n return transition;\n };\n\n StateNode.prototype.formatTransitions = function () {\n var e_10, _a;\n\n var _this = this;\n\n var onConfig;\n\n if (!this.config.on) {\n onConfig = [];\n } else if (Array.isArray(this.config.on)) {\n onConfig = this.config.on;\n } else {\n var _b = this.config.on,\n _c = WILDCARD,\n _d = _b[_c],\n wildcardConfigs = _d === void 0 ? [] : _d,\n strictTransitionConfigs_1 = __rest(_b, [typeof _c === \"symbol\" ? _c : _c + \"\"]);\n\n onConfig = flatten(Object.keys(strictTransitionConfigs_1).map(function (key) {\n if (!IS_PRODUCTION && key === NULL_EVENT) {\n warn(false, \"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. \" + \"Please check the `on` configuration for \\\"#\".concat(_this.id, \"\\\".\"));\n }\n\n var transitionConfigArray = toTransitionConfigArray(key, strictTransitionConfigs_1[key]);\n\n if (!IS_PRODUCTION) {\n validateArrayifiedTransitions(_this, key, transitionConfigArray);\n }\n\n return transitionConfigArray;\n }).concat(toTransitionConfigArray(WILDCARD, wildcardConfigs)));\n }\n\n var eventlessConfig = this.config.always ? toTransitionConfigArray('', this.config.always) : [];\n var doneConfig = this.config.onDone ? toTransitionConfigArray(String(done(this.id)), this.config.onDone) : [];\n\n if (!IS_PRODUCTION) {\n warn(!(this.config.onDone && !this.parent), \"Root nodes cannot have an \\\".onDone\\\" transition. Please check the config of \\\"\".concat(this.id, \"\\\".\"));\n }\n\n var invokeConfig = flatten(this.invoke.map(function (invokeDef) {\n var settleTransitions = [];\n\n if (invokeDef.onDone) {\n settleTransitions.push.apply(settleTransitions, __spreadArray([], __read(toTransitionConfigArray(String(doneInvoke(invokeDef.id)), invokeDef.onDone)), false));\n }\n\n if (invokeDef.onError) {\n settleTransitions.push.apply(settleTransitions, __spreadArray([], __read(toTransitionConfigArray(String(error(invokeDef.id)), invokeDef.onError)), false));\n }\n\n return settleTransitions;\n }));\n var delayedTransitions = this.after;\n var formattedTransitions = flatten(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(doneConfig), false), __read(invokeConfig), false), __read(onConfig), false), __read(eventlessConfig), false).map(function (transitionConfig) {\n return toArray(transitionConfig).map(function (transition) {\n return _this.formatTransition(transition);\n });\n }));\n\n try {\n for (var delayedTransitions_1 = __values(delayedTransitions), delayedTransitions_1_1 = delayedTransitions_1.next(); !delayedTransitions_1_1.done; delayedTransitions_1_1 = delayedTransitions_1.next()) {\n var delayedTransition = delayedTransitions_1_1.value;\n formattedTransitions.push(delayedTransition);\n }\n } catch (e_10_1) {\n e_10 = {\n error: e_10_1\n };\n } finally {\n try {\n if (delayedTransitions_1_1 && !delayedTransitions_1_1.done && (_a = delayedTransitions_1.return)) _a.call(delayedTransitions_1);\n } finally {\n if (e_10) throw e_10.error;\n }\n }\n\n return formattedTransitions;\n };\n\n return StateNode;\n}();\n\nexport { StateNode };\n","import { StateNode } from './StateNode.js';\nimport { IS_PRODUCTION } from './environment.js';\n\nvar warned = false;\nfunction Machine(config, options, initialContext) {\n if (initialContext === void 0) {\n initialContext = config.context;\n }\n\n return new StateNode(config, options, initialContext);\n}\nfunction createMachine(config, options) {\n if (!IS_PRODUCTION && !('predictableActionArguments' in config) && !warned) {\n warned = true;\n console.warn('It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html');\n }\n\n return new StateNode(config, options);\n}\n\nexport { Machine, createMachine };\n","import { __values } from './_virtual/_tslib.js';\nimport { matchesState } from './utils.js';\n\nfunction mapState(stateMap, stateId) {\n var e_1, _a;\n\n var foundStateId;\n\n try {\n for (var _b = __values(Object.keys(stateMap)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var mappedStateId = _c.value;\n\n if (matchesState(mappedStateId, stateId) && (!foundStateId || stateId.length > foundStateId.length)) {\n foundStateId = mappedStateId;\n }\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n\n return stateMap[foundStateId];\n}\n\nexport { mapState };\n","import { __values, __read } from './_virtual/_tslib.js';\nimport { State } from './State.js';\n\nfunction matchState(state, patterns, defaultValue) {\n var e_1, _a;\n\n var resolvedState = State.from(state, state instanceof State ? state.context : undefined);\n\n try {\n for (var patterns_1 = __values(patterns), patterns_1_1 = patterns_1.next(); !patterns_1_1.done; patterns_1_1 = patterns_1.next()) {\n var _b = __read(patterns_1_1.value, 2),\n stateValue = _b[0],\n getValue = _b[1];\n\n if (resolvedState.matches(stateValue)) {\n return getValue(resolvedState);\n }\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (patterns_1_1 && !patterns_1_1.done && (_a = patterns_1.return)) _a.call(patterns_1);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n\n return defaultValue(resolvedState);\n}\n\nexport { matchState };\n","function createSchema(schema) {\n return schema;\n}\nvar t = createSchema;\n\nexport { createSchema, t };\n","import { assign as assign$1, send as send$1, sendTo as sendTo$1, sendParent as sendParent$1, sendUpdate as sendUpdate$1, forwardTo as forwardTo$1, doneInvoke as doneInvoke$1, raise as raise$1 } from './actions.js';\nimport * as actions from './actions.js';\nexport { actions };\nexport { toActorRef } from './Actor.js';\nexport { Interpreter, InterpreterStatus, interpret, spawn } from './interpreter.js';\nexport { Machine, createMachine } from './Machine.js';\nexport { mapState } from './mapState.js';\nexport { matchState } from './match.js';\nexport { createSchema, t } from './schema.js';\nexport { State } from './State.js';\nexport { StateNode } from './StateNode.js';\nexport { spawnBehavior } from './behaviors.js';\nexport { ActionTypes, SpecialTargets } from './types.js';\nexport { matchesState, toEventObject, toObserver, toSCXMLEvent } from './utils.js';\n\nvar assign = assign$1,\n send = send$1,\n sendTo = sendTo$1,\n sendParent = sendParent$1,\n sendUpdate = sendUpdate$1,\n forwardTo = forwardTo$1,\n doneInvoke = doneInvoke$1,\n raise = raise$1;\n\nexport { assign, doneInvoke, forwardTo, raise, send, sendParent, sendTo, sendUpdate };\n","module.exports = __WEBPACK_EXTERNAL_MODULE__464__;","module.exports = __WEBPACK_EXTERNAL_MODULE__867__;","module.exports = __WEBPACK_EXTERNAL_MODULE__762__;","module.exports = __WEBPACK_EXTERNAL_MODULE__148__;","module.exports = __WEBPACK_EXTERNAL_MODULE__369__;","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nexport default function _toPropertyKey(arg) {\n var key = toPrimitive(arg, \"string\");\n return _typeof(key) === \"symbol\" ? key : String(key);\n}","import _typeof from \"./typeof.js\";\nexport default function _toPrimitive(input, hint) {\n if (_typeof(input) !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (_typeof(res) !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}","import toPropertyKey from \"./toPropertyKey.js\";\nexport default function _defineProperty(obj, key, value) {\n key = toPropertyKey(key);\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}","import e from\"void-elements\";var t=/\\s([^'\"/\\s><]+?)[\\s/>]|([^\\s=]+)=\\s?(\".*?\"|'.*?')/g;function n(n){var r={type:\"tag\",name:\"\",voidElement:!1,attrs:{},children:[]},i=n.match(/<\\/?([^\\s]+?)[/\\s>]/);if(i&&(r.name=i[1],(e[i[1]]||\"/\"===n.charAt(n.length-2))&&(r.voidElement=!0),r.name.startsWith(\"!--\"))){var s=n.indexOf(\"--\\x3e\");return{type:\"comment\",comment:-1!==s?n.slice(4,s):\"\"}}for(var a=new RegExp(t),c=null;null!==(c=a.exec(n));)if(c[0].trim())if(c[1]){var o=c[1].trim(),l=[o,\"\"];o.indexOf(\"=\")>-1&&(l=o.split(\"=\")),r.attrs[l[0]]=l[1],a.lastIndex--}else c[2]&&(r.attrs[c[2]]=c[3].trim().substring(1,c[3].length-1));return r}var r=/<[a-zA-Z0-9\\-\\!\\/](?:\"[^\"]*\"|'[^']*'|[^'\">])*>/g,i=/^\\s*$/,s=Object.create(null);function a(e,t){switch(t.type){case\"text\":return e+t.content;case\"tag\":return e+=\"<\"+t.name+(t.attrs?function(e){var t=[];for(var n in e)t.push(n+'=\"'+e[n]+'\"');return t.length?\" \"+t.join(\" \"):\"\"}(t.attrs):\"\")+(t.voidElement?\"/>\":\">\"),t.voidElement?e:e+t.children.reduce(a,\"\")+\"</\"+t.name+\">\";case\"comment\":return e+\"\\x3c!--\"+t.comment+\"--\\x3e\"}}var c={parse:function(e,t){t||(t={}),t.components||(t.components=s);var a,c=[],o=[],l=-1,m=!1;if(0!==e.indexOf(\"<\")){var u=e.indexOf(\"<\");c.push({type:\"text\",content:-1===u?e:e.substring(0,u)})}return e.replace(r,function(r,s){if(m){if(r!==\"</\"+a.name+\">\")return;m=!1}var u,f=\"/\"!==r.charAt(1),h=r.startsWith(\"\\x3c!--\"),p=s+r.length,d=e.charAt(p);if(h){var v=n(r);return l<0?(c.push(v),c):((u=o[l]).children.push(v),c)}if(f&&(l++,\"tag\"===(a=n(r)).type&&t.components[a.name]&&(a.type=\"component\",m=!0),a.voidElement||m||!d||\"<\"===d||a.children.push({type:\"text\",content:e.slice(p,e.indexOf(\"<\",p))}),0===l&&c.push(a),(u=o[l-1])&&u.children.push(a),o[l]=a),(!f||a.voidElement)&&(l>-1&&(a.voidElement||a.name===r.slice(2,-1))&&(l--,a=-1===l?c:o[l]),!m&&\"<\"!==d&&d)){u=-1===l?c:o[l].children;var x=e.indexOf(\"<\",p),g=e.slice(p,-1===x?void 0:x);i.test(g)&&(g=\" \"),(x>-1&&l+u.length>=0||\" \"!==g)&&u.push({type:\"text\",content:g})}}),c},stringify:function(e){return e.reduce(function(e,t){return e+a(\"\",t)},\"\")}};export default c;\n//# sourceMappingURL=html-parse-stringify.module.js.map\n","export function warn() {\n if (console && console.warn) {\n var _console;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n if (typeof args[0] === 'string') args[0] = \"react-i18next:: \".concat(args[0]);\n\n (_console = console).warn.apply(_console, args);\n }\n}\nvar alreadyWarned = {};\nexport function warnOnce() {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n if (typeof args[0] === 'string' && alreadyWarned[args[0]]) return;\n if (typeof args[0] === 'string') alreadyWarned[args[0]] = new Date();\n warn.apply(void 0, args);\n}\nexport function loadNamespaces(i18n, ns, cb) {\n i18n.loadNamespaces(ns, function () {\n if (i18n.isInitialized) {\n cb();\n } else {\n var initialized = function initialized() {\n setTimeout(function () {\n i18n.off('initialized', initialized);\n }, 0);\n cb();\n };\n\n i18n.on('initialized', initialized);\n }\n });\n}\n\nfunction oldI18nextHasLoadedNamespace(ns, i18n) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var lng = i18n.languages[0];\n var fallbackLng = i18n.options ? i18n.options.fallbackLng : false;\n var lastLng = i18n.languages[i18n.languages.length - 1];\n if (lng.toLowerCase() === 'cimode') return true;\n\n var loadNotPending = function loadNotPending(l, n) {\n var loadState = i18n.services.backendConnector.state[\"\".concat(l, \"|\").concat(n)];\n return loadState === -1 || loadState === 2;\n };\n\n if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18n.services.backendConnector.backend && i18n.isLanguageChangingTo && !loadNotPending(i18n.isLanguageChangingTo, ns)) return false;\n if (i18n.hasResourceBundle(lng, ns)) return true;\n if (!i18n.services.backendConnector.backend || i18n.options.resources && !i18n.options.partialBundledLanguages) return true;\n if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;\n return false;\n}\n\nexport function hasLoadedNamespace(ns, i18n) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n if (!i18n.languages || !i18n.languages.length) {\n warnOnce('i18n.languages were undefined or empty', i18n.languages);\n return true;\n }\n\n var isNewerI18next = i18n.options.ignoreJSONStructure !== undefined;\n\n if (!isNewerI18next) {\n return oldI18nextHasLoadedNamespace(ns, i18n, options);\n }\n\n return i18n.hasLoadedNamespace(ns, {\n precheck: function precheck(i18nInstance, loadNotPending) {\n if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false;\n }\n });\n}\nexport function getDisplayName(Component) {\n return Component.displayName || Component.name || (typeof Component === 'string' && Component.length > 0 ? Component : 'Unknown');\n}","var matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;\nvar htmlEntities = {\n '&': '&',\n '&': '&',\n '<': '<',\n '<': '<',\n '>': '>',\n '>': '>',\n ''': \"'\",\n ''': \"'\",\n '"': '\"',\n '"': '\"',\n ' ': ' ',\n ' ': ' ',\n '©': '©',\n '©': '©',\n '®': '®',\n '®': '®',\n '…': '…',\n '…': '…',\n '/': '/',\n '/': '/'\n};\n\nvar unescapeHtmlEntity = function unescapeHtmlEntity(m) {\n return htmlEntities[m];\n};\n\nexport var unescape = function unescape(text) {\n return text.replace(matchHtmlEntity, unescapeHtmlEntity);\n};","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\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(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nimport { unescape } from './unescape.js';\nvar defaultOptions = {\n bindI18n: 'languageChanged',\n bindI18nStore: '',\n transEmptyNodeValue: '',\n transSupportBasicHtmlNodes: true,\n transWrapTextNodes: '',\n transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],\n useSuspense: true,\n unescape: unescape\n};\nexport function setDefaults() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n defaultOptions = _objectSpread(_objectSpread({}, defaultOptions), options);\n}\nexport function getDefaults() {\n return defaultOptions;\n}","var i18nInstance;\nexport function setI18n(instance) {\n i18nInstance = instance;\n}\nexport function getI18n() {\n return i18nInstance;\n}","import toPropertyKey from \"./toPropertyKey.js\";\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);\n }\n}\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nimport _classCallCheck from \"@babel/runtime/helpers/classCallCheck\";\nimport _createClass from \"@babel/runtime/helpers/createClass\";\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(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nimport { createContext } from 'react';\nimport { getDefaults, setDefaults } from './defaults.js';\nimport { getI18n, setI18n } from './i18nInstance.js';\nimport { initReactI18next } from './initReactI18next.js';\nexport { getDefaults, setDefaults, getI18n, setI18n, initReactI18next };\nexport var I18nContext = createContext();\nexport var ReportNamespaces = function () {\n function ReportNamespaces() {\n _classCallCheck(this, ReportNamespaces);\n\n this.usedNamespaces = {};\n }\n\n _createClass(ReportNamespaces, [{\n key: \"addUsedNamespaces\",\n value: function addUsedNamespaces(namespaces) {\n var _this = this;\n\n namespaces.forEach(function (ns) {\n if (!_this.usedNamespaces[ns]) _this.usedNamespaces[ns] = true;\n });\n }\n }, {\n key: \"getUsedNamespaces\",\n value: function getUsedNamespaces() {\n return Object.keys(this.usedNamespaces);\n }\n }]);\n\n return ReportNamespaces;\n}();\nexport function composeInitialProps(ForComponent) {\n return function (ctx) {\n return new Promise(function (resolve) {\n var i18nInitialProps = getInitialProps();\n\n if (ForComponent.getInitialProps) {\n ForComponent.getInitialProps(ctx).then(function (componentsInitialProps) {\n resolve(_objectSpread(_objectSpread({}, componentsInitialProps), i18nInitialProps));\n });\n } else {\n resolve(i18nInitialProps);\n }\n });\n };\n}\nexport function getInitialProps() {\n var i18n = getI18n();\n var namespaces = i18n.reportNamespaces ? i18n.reportNamespaces.getUsedNamespaces() : [];\n var ret = {};\n var initialI18nStore = {};\n i18n.languages.forEach(function (l) {\n initialI18nStore[l] = {};\n namespaces.forEach(function (ns) {\n initialI18nStore[l][ns] = i18n.getResourceBundle(l, ns) || {};\n });\n });\n ret.initialI18nStore = initialI18nStore;\n ret.initialLanguage = i18n.language;\n return ret;\n}","export default function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}","export default function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n return arr2;\n}","import arrayWithHoles from \"./arrayWithHoles.js\";\nimport iterableToArrayLimit from \"./iterableToArrayLimit.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableRest from \"./nonIterableRest.js\";\nexport default function _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}","export default function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}","export default function _iterableToArrayLimit(arr, i) {\n var _i = null == arr ? null : \"undefined\" != typeof Symbol && arr[Symbol.iterator] || arr[\"@@iterator\"];\n if (null != _i) {\n var _s,\n _e,\n _x,\n _r,\n _arr = [],\n _n = !0,\n _d = !1;\n try {\n if (_x = (_i = _i.call(arr)).next, 0 === i) {\n if (Object(_i) !== _i) return;\n _n = !1;\n } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);\n } catch (err) {\n _d = !0, _e = err;\n } finally {\n try {\n if (!_n && null != _i[\"return\"] && (_r = _i[\"return\"](), Object(_r) !== _r)) return;\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n}","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nexport default function _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}","export default function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}","import _slicedToArray from \"@babel/runtime/helpers/slicedToArray\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nimport _typeof from \"@babel/runtime/helpers/typeof\";\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(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nimport { useState, useEffect, useContext, useRef } from 'react';\nimport { getI18n, getDefaults, ReportNamespaces, I18nContext } from './context.js';\nimport { warnOnce, loadNamespaces, hasLoadedNamespace } from './utils.js';\n\nvar usePrevious = function usePrevious(value, ignore) {\n var ref = useRef();\n useEffect(function () {\n ref.current = ignore ? ref.current : value;\n }, [value, ignore]);\n return ref.current;\n};\n\nexport function useTranslation(ns) {\n var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var i18nFromProps = props.i18n;\n\n var _ref = useContext(I18nContext) || {},\n i18nFromContext = _ref.i18n,\n defaultNSFromContext = _ref.defaultNS;\n\n var i18n = i18nFromProps || i18nFromContext || getI18n();\n if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();\n\n if (!i18n) {\n warnOnce('You will need to pass in an i18next instance by using initReactI18next');\n\n var notReadyT = function notReadyT(k, optsOrDefaultValue) {\n if (typeof optsOrDefaultValue === 'string') return optsOrDefaultValue;\n if (optsOrDefaultValue && _typeof(optsOrDefaultValue) === 'object' && typeof optsOrDefaultValue.defaultValue === 'string') return optsOrDefaultValue.defaultValue;\n return Array.isArray(k) ? k[k.length - 1] : k;\n };\n\n var retNotReady = [notReadyT, {}, false];\n retNotReady.t = notReadyT;\n retNotReady.i18n = {};\n retNotReady.ready = false;\n return retNotReady;\n }\n\n if (i18n.options.react && i18n.options.react.wait !== undefined) warnOnce('It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.');\n\n var i18nOptions = _objectSpread(_objectSpread(_objectSpread({}, getDefaults()), i18n.options.react), props);\n\n var useSuspense = i18nOptions.useSuspense,\n keyPrefix = i18nOptions.keyPrefix;\n var namespaces = ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS;\n namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation'];\n if (i18n.reportNamespaces.addUsedNamespaces) i18n.reportNamespaces.addUsedNamespaces(namespaces);\n var ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(function (n) {\n return hasLoadedNamespace(n, i18n, i18nOptions);\n });\n\n function getT() {\n return i18n.getFixedT(null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);\n }\n\n var _useState = useState(getT),\n _useState2 = _slicedToArray(_useState, 2),\n t = _useState2[0],\n setT = _useState2[1];\n\n var joinedNS = namespaces.join();\n var previousJoinedNS = usePrevious(joinedNS);\n var isMounted = useRef(true);\n useEffect(function () {\n var bindI18n = i18nOptions.bindI18n,\n bindI18nStore = i18nOptions.bindI18nStore;\n isMounted.current = true;\n\n if (!ready && !useSuspense) {\n loadNamespaces(i18n, namespaces, function () {\n if (isMounted.current) setT(getT);\n });\n }\n\n if (ready && previousJoinedNS && previousJoinedNS !== joinedNS && isMounted.current) {\n setT(getT);\n }\n\n function boundReset() {\n if (isMounted.current) setT(getT);\n }\n\n if (bindI18n && i18n) i18n.on(bindI18n, boundReset);\n if (bindI18nStore && i18n) i18n.store.on(bindI18nStore, boundReset);\n return function () {\n isMounted.current = false;\n if (bindI18n && i18n) bindI18n.split(' ').forEach(function (e) {\n return i18n.off(e, boundReset);\n });\n if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(function (e) {\n return i18n.store.off(e, boundReset);\n });\n };\n }, [i18n, joinedNS]);\n var isInitial = useRef(true);\n useEffect(function () {\n if (isMounted.current && !isInitial.current) {\n setT(getT);\n }\n\n isInitial.current = false;\n }, [i18n, keyPrefix]);\n var ret = [t, i18n, ready];\n ret.t = t;\n ret.i18n = i18n;\n ret.ready = ready;\n if (ready) return ret;\n if (!ready && !useSuspense) return ret;\n throw new Promise(function (resolve) {\n loadNamespaces(i18n, namespaces, function () {\n resolve();\n });\n });\n}","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","__webpack_require__.F = {};\n__webpack_require__.E = (chunkId) => {\n\tObject.keys(__webpack_require__.F).map((key) => {\n\t\t__webpack_require__.F[key](chunkId);\n\t});\n}","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.O(0, [143], () => {\n\t__webpack_require__.E(143);\n}, 5);","import React, { useState, useEffect } from 'react';\nimport PropTypes from 'prop-types';\nimport { utils } from '@ohif/core';\nimport {\n StudyBrowser,\n useImageViewer,\n useViewportGrid,\n Dialog,\n} from '@ohif/ui';\nimport { useTrackedMeasurements } from '../../getContextModule';\n\nconst { formatDate } = utils;\n\n/**\n *\n * @param {*} param0\n */\nfunction PanelStudyBrowserTracking({\n servicesManager,\n getImageSrc,\n getStudiesForPatientByMRN,\n requestDisplaySetCreationForStudy,\n dataSource,\n}) {\n const {\n measurementService,\n displaySetService,\n uiDialogService,\n hangingProtocolService,\n uiNotificationService,\n } = servicesManager.services;\n\n // Normally you nest the components so the tree isn't so deep, and the data\n // doesn't have to have such an intense shape. This works well enough for now.\n // Tabs --> Studies --> DisplaySets --> Thumbnails\n const { StudyInstanceUIDs } = useImageViewer();\n const [\n { activeViewportIndex, viewports, numCols, numRows },\n viewportGridService,\n ] = useViewportGrid();\n const [\n trackedMeasurements,\n sendTrackedMeasurementsEvent,\n ] = useTrackedMeasurements();\n const [activeTabName, setActiveTabName] = useState('primary');\n const [expandedStudyInstanceUIDs, setExpandedStudyInstanceUIDs] = useState([\n ...StudyInstanceUIDs,\n ]);\n const [studyDisplayList, setStudyDisplayList] = useState([]);\n const [displaySets, setDisplaySets] = useState([]);\n const [thumbnailImageSrcMap, setThumbnailImageSrcMap] = useState({});\n const [jumpToDisplaySet, setJumpToDisplaySet] = useState(null);\n\n const onDoubleClickThumbnailHandler = displaySetInstanceUID => {\n let updatedViewports = [];\n const viewportIndex = activeViewportIndex;\n try {\n updatedViewports = hangingProtocolService.getViewportsRequireUpdate(\n viewportIndex,\n displaySetInstanceUID\n );\n } catch (error) {\n console.warn(error);\n uiNotificationService.show({\n title: 'Thumbnail Double Click',\n message:\n 'The selected display sets could not be added to the viewport due to a mismatch in the Hanging Protocol rules.',\n type: 'info',\n duration: 3000,\n });\n }\n\n viewportGridService.setDisplaySetsForViewports(updatedViewports);\n };\n\n const activeViewportDisplaySetInstanceUIDs =\n viewports[activeViewportIndex]?.displaySetInstanceUIDs;\n\n useEffect(() => {\n const added = measurementService.EVENTS.MEASUREMENT_ADDED;\n const addedRaw = measurementService.EVENTS.RAW_MEASUREMENT_ADDED;\n const subscriptions = [];\n\n [added, addedRaw].forEach(evt => {\n subscriptions.push(\n measurementService.subscribe(evt, ({ source, measurement }) => {\n const {\n referenceSeriesUID: SeriesInstanceUID,\n referenceStudyUID: StudyInstanceUID,\n } = measurement;\n\n sendTrackedMeasurementsEvent('SET_DIRTY', { SeriesInstanceUID });\n sendTrackedMeasurementsEvent('TRACK_SERIES', {\n viewportIndex: activeViewportIndex,\n StudyInstanceUID,\n SeriesInstanceUID,\n });\n }).unsubscribe\n );\n });\n\n return () => {\n subscriptions.forEach(unsub => {\n unsub();\n });\n };\n }, [measurementService, activeViewportIndex, sendTrackedMeasurementsEvent]);\n\n const { trackedSeries } = trackedMeasurements.context;\n\n // ~~ studyDisplayList\n useEffect(() => {\n // Fetch all studies for the patient in each primary study\n async function fetchStudiesForPatient(StudyInstanceUID) {\n // current study qido\n const qidoForStudyUID = await dataSource.query.studies.search({\n studyInstanceUid: StudyInstanceUID,\n });\n\n let qidoStudiesForPatient = qidoForStudyUID;\n\n // try to fetch the prior studies based on the patientID if the\n // server can respond.\n try {\n qidoStudiesForPatient = await getStudiesForPatientByMRN(\n qidoForStudyUID\n );\n } catch (error) {\n console.warn(error);\n }\n\n const mappedStudies = _mapDataSourceStudies(qidoStudiesForPatient);\n const actuallyMappedStudies = mappedStudies.map(qidoStudy => {\n return {\n studyInstanceUid: qidoStudy.StudyInstanceUID,\n date: formatDate(qidoStudy.StudyDate),\n description: qidoStudy.StudyDescription,\n modalities: qidoStudy.ModalitiesInStudy,\n numInstances: qidoStudy.NumInstances,\n };\n });\n\n setStudyDisplayList(prevArray => {\n const ret = [...prevArray];\n for (const study of actuallyMappedStudies) {\n if (\n !prevArray.find(\n it => it.studyInstanceUid === study.studyInstanceUid\n )\n ) {\n ret.push(study);\n }\n }\n return ret;\n });\n }\n\n StudyInstanceUIDs.forEach(sid => fetchStudiesForPatient(sid));\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [StudyInstanceUIDs, getStudiesForPatientByMRN]);\n\n // ~~ Initial Thumbnails\n useEffect(() => {\n const currentDisplaySets = displaySetService.activeDisplaySets;\n\n if (!currentDisplaySets.length) {\n return;\n }\n\n currentDisplaySets.forEach(async dSet => {\n const newImageSrcEntry = {};\n const displaySet = displaySetService.getDisplaySetByUID(\n dSet.displaySetInstanceUID\n );\n const imageIds = dataSource.getImageIdsForDisplaySet(displaySet);\n const imageId = imageIds[Math.floor(imageIds.length / 2)];\n\n // TODO: Is it okay that imageIds are not returned here for SR displaysets?\n if (imageId) {\n // When the image arrives, render it and store the result in the thumbnailImgSrcMap\n newImageSrcEntry[dSet.displaySetInstanceUID] = await getImageSrc(\n imageId\n );\n setThumbnailImageSrcMap(prevState => {\n return { ...prevState, ...newImageSrcEntry };\n });\n }\n });\n }, [displaySetService, dataSource, getImageSrc]);\n\n // ~~ displaySets\n useEffect(() => {\n const currentDisplaySets = displaySetService.activeDisplaySets;\n\n if (!currentDisplaySets.length) {\n return;\n }\n\n const mappedDisplaySets = _mapDisplaySets(\n currentDisplaySets,\n thumbnailImageSrcMap,\n trackedSeries,\n viewports,\n viewportGridService,\n dataSource,\n displaySetService,\n uiDialogService,\n uiNotificationService\n );\n\n setDisplaySets(mappedDisplaySets);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n displaySetService.activeDisplaySets,\n trackedSeries,\n viewports,\n dataSource,\n thumbnailImageSrcMap,\n ]);\n\n // ~~ subscriptions --> displaySets\n useEffect(() => {\n // DISPLAY_SETS_ADDED returns an array of DisplaySets that were added\n const SubscriptionDisplaySetsAdded = displaySetService.subscribe(\n displaySetService.EVENTS.DISPLAY_SETS_ADDED,\n data => {\n const { displaySetsAdded, options } = data;\n displaySetsAdded.forEach(async dSet => {\n const displaySetInstanceUID = dSet.displaySetInstanceUID;\n\n const newImageSrcEntry = {};\n const displaySet = displaySetService.getDisplaySetByUID(\n displaySetInstanceUID\n );\n\n if (options.madeInClient) {\n setJumpToDisplaySet(displaySetInstanceUID);\n }\n\n const imageIds = dataSource.getImageIdsForDisplaySet(displaySet);\n const imageId = imageIds[Math.floor(imageIds.length / 2)];\n\n // TODO: Is it okay that imageIds are not returned here for SR displaysets?\n if (imageId) {\n // When the image arrives, render it and store the result in the thumbnailImgSrcMap\n newImageSrcEntry[displaySetInstanceUID] = await getImageSrc(\n imageId\n );\n setThumbnailImageSrcMap(prevState => {\n return { ...prevState, ...newImageSrcEntry };\n });\n }\n });\n }\n );\n\n // TODO: Will this always hold _all_ the displaySets we care about?\n // DISPLAY_SETS_CHANGED returns `DisplaySerService.activeDisplaySets`\n const SubscriptionDisplaySetsChanged = displaySetService.subscribe(\n displaySetService.EVENTS.DISPLAY_SETS_CHANGED,\n changedDisplaySets => {\n const mappedDisplaySets = _mapDisplaySets(\n changedDisplaySets,\n thumbnailImageSrcMap,\n trackedSeries,\n viewports,\n viewportGridService,\n dataSource,\n displaySetService,\n uiDialogService,\n uiNotificationService\n );\n\n setDisplaySets(mappedDisplaySets);\n }\n );\n\n return () => {\n SubscriptionDisplaySetsAdded.unsubscribe();\n SubscriptionDisplaySetsChanged.unsubscribe();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n displaySetService,\n dataSource,\n getImageSrc,\n thumbnailImageSrcMap,\n trackedSeries,\n viewports,\n ]);\n\n const tabs = _createStudyBrowserTabs(\n StudyInstanceUIDs,\n studyDisplayList,\n displaySets,\n hangingProtocolService\n );\n\n // TODO: Should not fire this on \"close\"\n function _handleStudyClick(StudyInstanceUID) {\n const shouldCollapseStudy = expandedStudyInstanceUIDs.includes(\n StudyInstanceUID\n );\n const updatedExpandedStudyInstanceUIDs = shouldCollapseStudy\n ? [\n ...expandedStudyInstanceUIDs.filter(\n stdyUid => stdyUid !== StudyInstanceUID\n ),\n ]\n : [...expandedStudyInstanceUIDs, StudyInstanceUID];\n\n setExpandedStudyInstanceUIDs(updatedExpandedStudyInstanceUIDs);\n\n if (!shouldCollapseStudy) {\n const madeInClient = true;\n requestDisplaySetCreationForStudy(\n displaySetService,\n StudyInstanceUID,\n madeInClient\n );\n }\n }\n\n useEffect(() => {\n if (jumpToDisplaySet) {\n // Get element by displaySetInstanceUID\n const displaySetInstanceUID = jumpToDisplaySet;\n const element = document.getElementById(\n `thumbnail-${displaySetInstanceUID}`\n );\n\n if (element && typeof element.scrollIntoView === 'function') {\n // TODO: Any way to support IE here?\n element.scrollIntoView({ behavior: 'smooth' });\n\n setJumpToDisplaySet(null);\n }\n }\n }, [jumpToDisplaySet, expandedStudyInstanceUIDs, activeTabName]);\n\n useEffect(() => {\n if (!jumpToDisplaySet) {\n return;\n }\n\n const displaySetInstanceUID = jumpToDisplaySet;\n // Set the activeTabName and expand the study\n const thumbnailLocation = _findTabAndStudyOfDisplaySet(\n displaySetInstanceUID,\n tabs\n );\n if (!thumbnailLocation) {\n console.warn('jumpToThumbnail: displaySet thumbnail not found.');\n\n return;\n }\n const { tabName, StudyInstanceUID } = thumbnailLocation;\n setActiveTabName(tabName);\n const studyExpanded = expandedStudyInstanceUIDs.includes(StudyInstanceUID);\n if (!studyExpanded) {\n const updatedExpandedStudyInstanceUIDs = [\n ...expandedStudyInstanceUIDs,\n StudyInstanceUID,\n ];\n setExpandedStudyInstanceUIDs(updatedExpandedStudyInstanceUIDs);\n }\n }, [expandedStudyInstanceUIDs, jumpToDisplaySet, tabs]);\n\n return (\n <StudyBrowser\n tabs={tabs}\n servicesManager={servicesManager}\n activeTabName={activeTabName}\n expandedStudyInstanceUIDs={expandedStudyInstanceUIDs}\n onClickStudy={_handleStudyClick}\n onClickTab={clickedTabName => {\n setActiveTabName(clickedTabName);\n }}\n onClickUntrack={displaySetInstanceUID => {\n const displaySet = displaySetService.getDisplaySetByUID(\n displaySetInstanceUID\n );\n // TODO: shift this somewhere else where we're centralizing this logic?\n // Potentially a helper from displaySetInstanceUID to this\n sendTrackedMeasurementsEvent('UNTRACK_SERIES', {\n SeriesInstanceUID: displaySet.SeriesInstanceUID,\n });\n }}\n onClickThumbnail={() => {}}\n onDoubleClickThumbnail={onDoubleClickThumbnailHandler}\n activeDisplaySetInstanceUIDs={activeViewportDisplaySetInstanceUIDs}\n />\n );\n}\n\nPanelStudyBrowserTracking.propTypes = {\n servicesManager: PropTypes.object.isRequired,\n dataSource: PropTypes.shape({\n getImageIdsForDisplaySet: PropTypes.func.isRequired,\n }).isRequired,\n getImageSrc: PropTypes.func.isRequired,\n getStudiesForPatientByMRN: PropTypes.func.isRequired,\n requestDisplaySetCreationForStudy: PropTypes.func.isRequired,\n};\n\nexport default PanelStudyBrowserTracking;\n\n/**\n * Maps from the DataSource's format to a naturalized object\n *\n * @param {*} studies\n */\nfunction _mapDataSourceStudies(studies) {\n return studies.map(study => {\n // TODO: Why does the data source return in this format?\n return {\n AccessionNumber: study.accession,\n StudyDate: study.date,\n StudyDescription: study.description,\n NumInstances: study.instances,\n ModalitiesInStudy: study.modalities,\n PatientID: study.mrn,\n PatientName: study.patientName,\n StudyInstanceUID: study.studyInstanceUid,\n StudyTime: study.time,\n };\n });\n}\n\nfunction _mapDisplaySets(\n displaySets,\n thumbnailImageSrcMap,\n trackedSeriesInstanceUIDs,\n viewports, // TODO: make array of `displaySetInstanceUIDs`?\n viewportGridService,\n dataSource,\n displaySetService,\n uiDialogService,\n uiNotificationService\n) {\n const thumbnailDisplaySets = [];\n const thumbnailNoImageDisplaySets = [];\n displaySets\n .filter(ds => !ds.excludeFromThumbnailBrowser)\n .forEach(ds => {\n const imageSrc = thumbnailImageSrcMap[ds.displaySetInstanceUID];\n const componentType = _getComponentType(ds.Modality);\n const numPanes = viewportGridService.getNumViewportPanes();\n const viewportIdentificator =\n numPanes === 1\n ? []\n : viewports.reduce((acc, viewportData, index) => {\n if (\n index < numPanes &&\n viewportData?.displaySetInstanceUIDs?.includes(\n ds.displaySetInstanceUID\n )\n ) {\n acc.push(viewportData.viewportLabel);\n }\n return acc;\n }, []);\n\n const array =\n componentType === 'thumbnailTracked'\n ? thumbnailDisplaySets\n : thumbnailNoImageDisplaySets;\n\n const { displaySetInstanceUID } = ds;\n\n const thumbnailProps = {\n displaySetInstanceUID,\n description: ds.SeriesDescription,\n seriesNumber: ds.SeriesNumber,\n modality: ds.Modality,\n seriesDate: formatDate(ds.SeriesDate),\n numInstances: ds.numImageFrames,\n countIcon: ds.countIcon,\n StudyInstanceUID: ds.StudyInstanceUID,\n componentType,\n imageSrc,\n dragData: {\n type: 'displayset',\n displaySetInstanceUID,\n // .. Any other data to pass\n },\n isTracked: trackedSeriesInstanceUIDs.includes(ds.SeriesInstanceUID),\n viewportIdentificator,\n };\n\n if (componentType === 'thumbnailNoImage') {\n if (dataSource.reject && dataSource.reject.series) {\n thumbnailProps.canReject = true;\n thumbnailProps.onReject = () => {\n uiDialogService.create({\n id: 'ds-reject-sr',\n centralize: true,\n isDraggable: false,\n showOverlay: true,\n content: Dialog,\n contentProps: {\n title: 'Delete Report',\n body: () => (\n <div className=\"p-4 text-white bg-primary-dark\">\n <p>Are you sure you want to delete this report?</p>\n <p>This action cannot be undone.</p>\n </div>\n ),\n actions: [\n { id: 'cancel', text: 'Cancel', type: 'secondary' },\n {\n id: 'yes',\n text: 'Yes',\n type: 'primary',\n classes: ['reject-yes-button'],\n },\n ],\n onClose: () => uiDialogService.dismiss({ id: 'ds-reject-sr' }),\n onShow: () => {\n const yesButton = document.querySelector(\n '.reject-yes-button'\n );\n\n yesButton.focus();\n },\n onSubmit: async ({ action }) => {\n switch (action.id) {\n case 'yes':\n try {\n await dataSource.reject.series(\n ds.StudyInstanceUID,\n ds.SeriesInstanceUID\n );\n displaySetService.deleteDisplaySet(\n displaySetInstanceUID\n );\n uiDialogService.dismiss({ id: 'ds-reject-sr' });\n uiNotificationService.show({\n title: 'Delete Report',\n message: 'Report deleted successfully',\n type: 'success',\n });\n } catch (error) {\n uiDialogService.dismiss({ id: 'ds-reject-sr' });\n uiNotificationService.show({\n title: 'Delete Report',\n message: 'Failed to delete report',\n type: 'error',\n });\n }\n break;\n case 'cancel':\n uiDialogService.dismiss({ id: 'ds-reject-sr' });\n break;\n }\n },\n },\n });\n };\n } else {\n thumbnailProps.canReject = false;\n }\n }\n\n array.push(thumbnailProps);\n });\n\n return [...thumbnailDisplaySets, ...thumbnailNoImageDisplaySets];\n}\n\nconst thumbnailNoImageModalities = [\n 'SR',\n 'SEG',\n 'SM',\n 'RTSTRUCT',\n 'RTPLAN',\n 'RTDOSE',\n 'DOC',\n 'OT',\n];\n\nfunction _getComponentType(Modality) {\n if (thumbnailNoImageModalities.includes(Modality)) {\n return 'thumbnailNoImage';\n }\n\n return 'thumbnailTracked';\n}\n\n/**\n *\n * @param {string[]} primaryStudyInstanceUIDs\n * @param {object[]} studyDisplayList\n * @param {string} studyDisplayList.studyInstanceUid\n * @param {string} studyDisplayList.date\n * @param {string} studyDisplayList.description\n * @param {string} studyDisplayList.modalities\n * @param {number} studyDisplayList.numInstances\n * @param {object[]} displaySets\n * @returns tabs - The prop object expected by the StudyBrowser component\n */\nfunction _createStudyBrowserTabs(\n primaryStudyInstanceUIDs,\n studyDisplayList,\n displaySets,\n hangingProtocolService\n) {\n const primaryStudies = [];\n const recentStudies = [];\n const allStudies = [];\n\n // Iterate over each study...\n studyDisplayList.forEach(study => {\n // Find it's display sets\n const displaySetsForStudy = displaySets.filter(\n ds => ds.StudyInstanceUID === study.studyInstanceUid\n );\n\n // Sort them\n const dsSortFn = hangingProtocolService.getDisplaySetSortFunction();\n displaySetsForStudy.sort(dsSortFn);\n\n /* Sort by series number, then by series date\n displaySetsForStudy.sort((a, b) => {\n if (a.seriesNumber !== b.seriesNumber) {\n return a.seriesNumber - b.seriesNumber;\n }\n\n const seriesDateA = Date.parse(a.seriesDate);\n const seriesDateB = Date.parse(b.seriesDate);\n\n return seriesDateA - seriesDateB;\n });\n */\n\n // Map the study to it's tab/view representation\n const tabStudy = Object.assign({}, study, {\n displaySets: displaySetsForStudy,\n });\n\n // Add the \"tab study\" to the 'primary', 'recent', and/or 'all' tab group(s)\n if (primaryStudyInstanceUIDs.includes(study.studyInstanceUid)) {\n primaryStudies.push(tabStudy);\n allStudies.push(tabStudy);\n } else {\n // TODO: Filter allStudies to dates within one year of current date\n recentStudies.push(tabStudy);\n allStudies.push(tabStudy);\n }\n });\n\n // Newest first\n const _byDate = (a, b) => {\n const dateA = Date.parse(a);\n const dateB = Date.parse(b);\n\n return dateB - dateA;\n };\n\n const tabs = [\n {\n name: 'primary',\n label: 'Primary',\n studies: primaryStudies.sort((studyA, studyB) =>\n _byDate(studyA.date, studyB.date)\n ),\n },\n {\n name: 'recent',\n label: 'Recent',\n studies: recentStudies.sort((studyA, studyB) =>\n _byDate(studyA.date, studyB.date)\n ),\n },\n {\n name: 'all',\n label: 'All',\n studies: allStudies.sort((studyA, studyB) =>\n _byDate(studyA.date, studyB.date)\n ),\n },\n ];\n\n return tabs;\n}\n\nfunction _findTabAndStudyOfDisplaySet(displaySetInstanceUID, tabs) {\n for (let t = 0; t < tabs.length; t++) {\n const { studies } = tabs[t];\n\n for (let s = 0; s < studies.length; s++) {\n const { displaySets } = studies[s];\n\n for (let d = 0; d < displaySets.length; d++) {\n const displaySet = displaySets[d];\n\n if (displaySet.displaySetInstanceUID === displaySetInstanceUID) {\n return {\n tabName: tabs[t].name,\n StudyInstanceUID: studies[s].studyInstanceUid,\n };\n }\n }\n }\n }\n}\n","/**\n * @param {*} cornerstone\n * @param {*} imageId\n */\nfunction getImageSrcFromImageId(cornerstone, imageId) {\n return new Promise((resolve, reject) => {\n const canvas = document.createElement('canvas');\n cornerstone.utilities\n .loadImageToCanvas({ canvas, imageId })\n .then(imageId => {\n resolve(canvas.toDataURL());\n })\n .catch(reject);\n });\n}\n\nexport default getImageSrcFromImageId;\n","function requestDisplaySetCreationForStudy(\n dataSource,\n displaySetService,\n StudyInstanceUID,\n madeInClient\n) {\n if (\n displaySetService.activeDisplaySets.some(\n displaySet => displaySet.StudyInstanceUID === StudyInstanceUID\n )\n ) {\n return;\n }\n\n dataSource.retrieve.series.metadata({ StudyInstanceUID, madeInClient });\n}\n\nexport default requestDisplaySetCreationForStudy;\n","import React from 'react';\nimport PropTypes from 'prop-types';\n//\nimport PanelStudyBrowserTracking from './PanelStudyBrowserTracking';\nimport getImageSrcFromImageId from './getImageSrcFromImageId';\nimport requestDisplaySetCreationForStudy from './requestDisplaySetCreationForStudy';\n\nfunction _getStudyForPatientUtility(extensionManager) {\n const utilityModule = extensionManager.getModuleEntry(\n '@ohif/extension-default.utilityModule.common'\n );\n\n const { getStudiesForPatientByMRN } = utilityModule.exports;\n return getStudiesForPatientByMRN;\n}\n\n/**\n * Wraps the PanelStudyBrowser and provides features afforded by managers/services\n *\n * @param {object} params\n * @param {object} commandsManager\n * @param {object} extensionManager\n */\nfunction WrappedPanelStudyBrowserTracking({\n commandsManager,\n extensionManager,\n servicesManager,\n}) {\n const dataSource = extensionManager.getActiveDataSource()[0];\n\n const getStudiesForPatientByMRN = _getStudyForPatientUtility(\n extensionManager\n );\n const _getStudiesForPatientByMRN = getStudiesForPatientByMRN.bind(\n null,\n dataSource\n );\n const _getImageSrcFromImageId = _createGetImageSrcFromImageIdFn(\n extensionManager\n );\n const _requestDisplaySetCreationForStudy = requestDisplaySetCreationForStudy.bind(\n null,\n dataSource\n );\n\n return (\n <PanelStudyBrowserTracking\n servicesManager={servicesManager}\n dataSource={dataSource}\n getImageSrc={_getImageSrcFromImageId}\n getStudiesForPatientByMRN={_getStudiesForPatientByMRN}\n requestDisplaySetCreationForStudy={_requestDisplaySetCreationForStudy}\n />\n );\n}\n\n/**\n * Grabs cornerstone library reference using a dependent command from\n * the @ohif/extension-cornerstone extension. Then creates a helper function\n * that can take an imageId and return an image src.\n *\n * @param {func} getCommand - CommandManager's getCommand method\n * @returns {func} getImageSrcFromImageId - A utility function powered by\n * cornerstone\n */\nfunction _createGetImageSrcFromImageIdFn(extensionManager) {\n const utilities = extensionManager.getModuleEntry(\n '@ohif/extension-cornerstone.utilityModule.common'\n );\n\n try {\n const { cornerstone } = utilities.exports.getCornerstoneLibraries();\n return getImageSrcFromImageId.bind(null, cornerstone);\n } catch (ex) {\n throw new Error('Required command not found');\n }\n}\n\nWrappedPanelStudyBrowserTracking.propTypes = {\n commandsManager: PropTypes.object.isRequired,\n extensionManager: PropTypes.object.isRequired,\n servicesManager: PropTypes.object.isRequired,\n};\n\nexport default WrappedPanelStudyBrowserTracking;\n","/**\n * @remix-run/router v1.5.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 */\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\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n return _extends.apply(this, arguments);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nvar Action;\n\n(function (Action) {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Action[\"Pop\"] = \"POP\";\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n\n Action[\"Push\"] = \"PUSH\";\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n\n Action[\"Replace\"] = \"REPLACE\";\n})(Action || (Action = {}));\n\nconst PopStateEventType = \"popstate\";\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\n\nfunction createMemoryHistory(options) {\n if (options === void 0) {\n options = {};\n }\n\n let {\n initialEntries = [\"/\"],\n initialIndex,\n v5Compat = false\n } = options;\n let entries; // Declare so we can access from createMemoryLocation\n\n entries = initialEntries.map((entry, index) => 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\n function clampIndex(n) {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n\n function getCurrentLocation() {\n return entries[index];\n }\n\n function createMemoryLocation(to, state, key) {\n if (state === void 0) {\n state = null;\n }\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\n function createHref(to) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history = {\n get index() {\n return index;\n },\n\n get action() {\n return action;\n },\n\n get location() {\n return getCurrentLocation();\n },\n\n createHref,\n\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\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\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\n if (v5Compat && listener) {\n listener({\n action,\n location: nextLocation,\n delta: 1\n });\n }\n },\n\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n\n if (v5Compat && listener) {\n listener({\n action,\n location: nextLocation,\n delta: 0\n });\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\n if (listener) {\n listener({\n action,\n location: nextLocation,\n delta\n });\n }\n },\n\n listen(fn) {\n listener = fn;\n return () => {\n listener = null;\n };\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 */\n\nfunction createBrowserHistory(options) {\n if (options === void 0) {\n options = {};\n }\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 }, // state defaults to `null` because `window.history.state` does\n globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n }\n\n function createBrowserHref(window, to) {\n return typeof to === \"string\" ? to : createPath(to);\n }\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 */\n\nfunction createHashHistory(options) {\n if (options === void 0) {\n options = {};\n }\n\n function createHashLocation(window, globalHistory) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\"\n } = parsePath(window.location.hash.substr(1));\n return createLocation(\"\", {\n pathname,\n search,\n hash\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\n function createHashHref(window, to) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\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\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\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\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\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); // eslint-disable-next-line no-empty\n } catch (e) {}\n }\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 */\n\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 */\n\n\nfunction createLocation(current, to, state, key) {\n if (state === void 0) {\n state = null;\n }\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\n return location;\n}\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\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 */\n\nfunction parsePath(path) {\n let parsedPath = {};\n\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n let searchIndex = path.indexOf(\"?\");\n\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nfunction getUrlBasedHistory(getLocation, createHref, validateLocation, options) {\n if (options === void 0) {\n options = {};\n }\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(); // 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\n if (index == null) {\n index = 0;\n globalHistory.replaceState(_extends({}, globalHistory.state, {\n idx: index\n }), \"\");\n }\n\n function getIndex() {\n let state = globalHistory.state || {\n idx: null\n };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n\n if (listener) {\n listener({\n action,\n location: history.location,\n delta\n });\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); // try...catch because iOS limits us to 100 pushState calls :/\n\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\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\n if (v5Compat && listener) {\n listener({\n action,\n location: history.location,\n delta: 1\n });\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\n if (v5Compat && listener) {\n listener({\n action,\n location: history.location,\n delta: 0\n });\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 invariant(base, \"No window.location.(origin|href) available to create URL for href: \" + href);\n return new URL(href, base);\n }\n\n let history = {\n get action() {\n return action;\n },\n\n get location() {\n return getLocation(window, globalHistory);\n },\n\n listen(fn) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n\n createHref(to) {\n return createHref(window, to);\n },\n\n createURL,\n\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\n push,\n replace,\n\n go(n) {\n return globalHistory.go(n);\n }\n\n };\n return history;\n} //#endregion\n\nvar ResultType;\n\n(function (ResultType) {\n ResultType[\"data\"] = \"data\";\n ResultType[\"deferred\"] = \"deferred\";\n ResultType[\"redirect\"] = \"redirect\";\n ResultType[\"error\"] = \"error\";\n})(ResultType || (ResultType = {}));\n\nconst immutableRouteKeys = new Set([\"lazy\", \"caseSensitive\", \"path\", \"id\", \"index\", \"children\"]);\n\nfunction isIndexRoute(route) {\n return route.index === true;\n} // Walk the route tree generating unique IDs where necessary so we are working\n// solely with AgnosticDataRouteObject's within the Router\n\n\nfunction convertRoutesToDataRoutes(routes, detectErrorBoundary, parentPath, manifest) {\n if (parentPath === void 0) {\n parentPath = [];\n }\n\n if (manifest === void 0) {\n manifest = {};\n }\n\n return routes.map((route, index) => {\n let treePath = [...parentPath, 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\n if (isIndexRoute(route)) {\n let indexRoute = _extends({}, route, {\n hasErrorBoundary: detectErrorBoundary(route),\n id\n });\n\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute = _extends({}, route, {\n id,\n hasErrorBoundary: detectErrorBoundary(route),\n children: undefined\n });\n\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, detectErrorBoundary, treePath, manifest);\n }\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 */\n\nfunction matchRoutes(routes, locationArg, basename) {\n if (basename === void 0) {\n basename = \"/\";\n }\n\n let location = typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n let pathname = stripBasename(location.pathname || \"/\", basename);\n\n if (pathname == null) {\n return null;\n }\n\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n let matches = null;\n\n for (let i = 0; matches == null && i < branches.length; ++i) {\n matches = matchRouteBranch(branches[i], // 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 safelyDecodeURI(pathname));\n }\n\n return matches;\n}\n\nfunction flattenRoutes(routes, branches, parentsMeta, parentPath) {\n if (branches === void 0) {\n branches = [];\n }\n\n if (parentsMeta === void 0) {\n parentsMeta = [];\n }\n\n if (parentPath === void 0) {\n parentPath = \"\";\n }\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\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\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta); // 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\n if (route.children && route.children.length > 0) {\n invariant( // 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 } // 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\n\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta\n });\n };\n\n routes.forEach((route, index) => {\n var _route$path;\n\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 */\n\n\nfunction explodeOptionalSegments(path) {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n let [first, ...rest] = segments; // Optional path segments are denoted by a trailing `?`\n\n let isOptional = first.endsWith(\"?\"); // Compute the corresponding required segment: `foo?` -> `foo`\n\n let required = first.replace(/\\?$/, \"\");\n\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\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n let result = []; // 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 explodes _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n\n result.push(...restExploded.map(subpath => subpath === \"\" ? required : [required, subpath].join(\"/\"))); // Then if this is an optional value, add all child versions without\n\n if (isOptional) {\n result.push(...restExploded);\n } // for absolute paths, ensure `/` instead of empty segment\n\n\n return result.map(exploded => path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded);\n}\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}\n\nconst paramRe = /^:\\w+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\n\nconst isSplat = s => s === \"*\";\n\nfunction computeScore(path, index) {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === \"\" ? emptySegmentValue : staticSegmentValue), initialScore);\n}\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 ? // 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] : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch(branch, pathname) {\n let {\n routesMeta\n } = branch;\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches = [];\n\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 if (!match) return null;\n Object.assign(matchedParams, match.params);\n let route = meta.route;\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\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n\n return matches;\n}\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/utils/generate-path\n */\n\n\nfunction generatePath(originalPath, params) {\n if (params === void 0) {\n params = {};\n }\n\n let path = originalPath;\n\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 } // ensure `/` is added at the beginning if the path is absolute\n\n\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n const segments = path.split(/\\/+/).map((segment, index, array) => {\n const isLastSegment = index === array.length - 1; // only apply the splat if it's the last segment\n\n if (isLastSegment && segment === \"*\") {\n const star = \"*\";\n const starParam = params[star]; // Apply the splat\n\n return starParam;\n }\n\n const keyMatch = segment.match(/^:(\\w+)(\\??)$/);\n\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key];\n\n if (optional === \"?\") {\n return param == null ? \"\" : param;\n }\n\n if (param == null) {\n invariant(false, \"Missing \\\":\" + key + \"\\\" param\");\n }\n\n return param;\n } // Remove any optional markers from optional static segments\n\n\n return segment.replace(/\\?$/g, \"\");\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 */\n\nfunction matchPath(pattern, pathname) {\n if (typeof pattern === \"string\") {\n pattern = {\n path: pattern,\n caseSensitive: false,\n end: true\n };\n }\n\n let [matcher, paramNames] = 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 = paramNames.reduce((memo, paramName, index) => {\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\n memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || \"\", paramName);\n return memo;\n }, {});\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern\n };\n}\n\nfunction compilePath(path, caseSensitive, end) {\n if (caseSensitive === void 0) {\n caseSensitive = false;\n }\n\n if (end === void 0) {\n end = true;\n }\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 paramNames = [];\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) => {\n paramNames.push(paramName);\n return \"/([^\\\\/]+)\";\n });\n\n if (path.endsWith(\"*\")) {\n paramNames.push(\"*\");\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\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n return [matcher, paramNames];\n}\n\nfunction safelyDecodeURI(value) {\n try {\n return decodeURI(value);\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\nfunction safelyDecodeURIComponent(value, paramName) {\n try {\n return decodeURIComponent(value);\n } catch (error) {\n warning(false, \"The value for the URL param \\\"\" + paramName + \"\\\" will not be decoded because\" + (\" the string \\\"\" + value + \"\\\" is a malformed URL segment. This is probably\") + (\" due to a bad percent encoding (\" + error + \").\"));\n return value;\n }\n}\n/**\n * @private\n */\n\n\nfunction stripBasename(pathname, basename) {\n if (basename === \"/\") return pathname;\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\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\n\n let startIndex = basename.endsWith(\"/\") ? basename.length - 1 : basename.length;\n let nextChar = pathname.charAt(startIndex);\n\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\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 */\n\nfunction resolvePath(to, fromPathname) {\n if (fromPathname === void 0) {\n fromPathname = \"/\";\n }\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}\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}\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 <Link to=\\\"...\\\"> 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 * <Route path=\"/\">\n * <Route path=\"accounts\" element={<Link to=\"..\"}>\n * </Route>\n *\n * <Route path=\"/\">\n * <Route path=\"accounts\">\n * <Route element={<AccountsLayout />}> // <-- Does not contribute\n * <Route index element={<Link to=\"..\"} /> // <-- Does not contribute\n * </Route\n * </Route>\n * </Route>\n */\n\n\nfunction getPathContributingMatches(matches) {\n return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);\n}\n/**\n * @private\n */\n\nfunction resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {\n if (isPathRelative === void 0) {\n isPathRelative = false;\n }\n\n let to;\n\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\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n let from; // 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 `<Link to>` 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\n if (isPathRelative || toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n if (toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\"); // Each leading .. segment means \"go up one route\" instead of \"go up one\n // URL segment\". This is a key difference from how <a href> works and a\n // major reason we call this a \"to\" value instead of a \"href\".\n\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n } // If there are more \"..\" segments than parent routes, resolve relative to\n // the root / URL.\n\n\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from); // Ensure the pathname has a trailing slash if the original \"to\" had one\n\n let hasExplicitTrailingSlash = toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\"); // Or if this was a link to the current path which has a trailing slash\n\n let hasCurrentTrailingSlash = (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n\n if (!path.pathname.endsWith(\"/\") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n/**\n * @private\n */\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 */\n\nconst joinPaths = paths => paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n/**\n * @private\n */\n\nconst normalizePathname = pathname => pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n/**\n * @private\n */\n\nconst normalizeSearch = search => !search || search === \"?\" ? \"\" : search.startsWith(\"?\") ? search : \"?\" + search;\n/**\n * @private\n */\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 */\n\nconst json = function json(data, init) {\n if (init === void 0) {\n init = {};\n }\n\n let responseInit = typeof init === \"number\" ? {\n status: init\n } : init;\n let headers = new Headers(responseInit.headers);\n\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\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\"); // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n\n let reject;\n this.abortPromise = new Promise((_, r) => reject = r);\n this.controller = new AbortController();\n\n let onAbort = () => reject(new AbortedDeferredError(\"Deferred data aborted\"));\n\n this.unlistenAbortSignal = () => this.controller.signal.removeEventListener(\"abort\", onAbort);\n\n this.controller.signal.addEventListener(\"abort\", onAbort);\n this.data = Object.entries(data).reduce((acc, _ref) => {\n let [key, value] = _ref;\n return Object.assign(acc, {\n [key]: this.trackPromise(key, value)\n });\n }, {});\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n trackPromise(key, value) {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key); // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n\n let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, null, data), error => this.onSettle(promise, key, error)); // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n\n promise.catch(() => {});\n Object.defineProperty(promise, \"_tracked\", {\n get: () => true\n });\n return promise;\n }\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\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n if (error) {\n Object.defineProperty(promise, \"_error\", {\n get: () => error\n });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", {\n get: () => data\n });\n this.emit(false, key);\n return data;\n }\n\n emit(aborted, settledKey) {\n this.subscribers.forEach(subscriber => subscriber(aborted, settledKey));\n }\n\n subscribe(fn) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal) {\n let aborted = false;\n\n if (!this.done) {\n let onAbort = () => this.cancel();\n\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise(resolve => {\n this.subscribe(aborted => {\n signal.removeEventListener(\"abort\", onAbort);\n\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\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, _ref2) => {\n let [key, value] = _ref2;\n return Object.assign(acc, {\n [key]: unwrapTrackedPromise(value)\n });\n }, {});\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n\n}\n\nfunction isTrackedPromise(value) {\n return value instanceof Promise && value._tracked === true;\n}\n\nfunction unwrapTrackedPromise(value) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n\n return value._data;\n}\n\nconst defer = function defer(data, init) {\n if (init === void 0) {\n init = {};\n }\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 */\n\nconst redirect = function redirect(url, init) {\n if (init === void 0) {\n init = 302;\n }\n\n let responseInit = init;\n\n if (typeof responseInit === \"number\") {\n responseInit = {\n status: responseInit\n };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\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 * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n */\n\nclass ErrorResponse {\n constructor(status, statusText, data, internal) {\n if (internal === void 0) {\n internal = false;\n }\n\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n\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/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\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};\nconst IDLE_FETCHER = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: 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 isBrowser = typeof window !== \"undefined\" && typeof window.document !== \"undefined\" && typeof window.document.createElement !== \"undefined\";\nconst isServer = !isBrowser;\n\nconst defaultDetectErrorBoundary = route => Boolean(route.hasErrorBoundary); //#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\n\n\nfunction createRouter(init) {\n invariant(init.routes.length > 0, \"You must provide a non-empty routes array to createRouter\");\n let detectErrorBoundary = init.detectErrorBoundary || defaultDetectErrorBoundary; // Routes keyed by ID\n\n let manifest = {}; // Routes in tree format for matching\n\n let dataRoutes = convertRoutesToDataRoutes(init.routes, detectErrorBoundary, undefined, manifest);\n let inFlightDataRoutes; // Config driven behavior flags\n\n let future = _extends({\n v7_normalizeFormMethod: false\n }, init.future); // Cleanup function for history\n\n\n let unlistenHistory = null; // Externally-provided functions to call on all state changes\n\n let subscribers = new Set(); // Externally-provided object to hold scroll restoration locations during routing\n\n let savedScrollPositions = null; // Externally-provided function to get scroll restoration keys\n\n let getScrollRestorationKey = null; // Externally-provided function to get current scroll position\n\n let getScrollPosition = null; // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from <ScrollRestoration /> 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\n let initialScrollRestored = init.hydrationData != null;\n let initialMatches = matchRoutes(dataRoutes, init.history.location, init.basename);\n let initialErrors = null;\n\n if (initialMatches == null) {\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\n let initialized = // 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 !initialMatches.some(m => m.route.lazy) && ( // And we have to either have no loaders or have been provided hydrationData\n !initialMatches.some(m => m.route.loader) || init.hydrationData != null);\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 }; // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n\n let pendingAction = Action.Pop; // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n\n let pendingPreventScrollReset = false; // AbortController for the active navigation\n\n let pendingNavigationController; // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n\n let isUninterruptedRevalidation = false; // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidate()\n // - X-Remix-Revalidate (from redirect)\n\n let isRevalidationRequired = false; // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n\n let cancelledDeferredRoutes = []; // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n\n let cancelledFetcherLoads = []; // AbortControllers for any in-flight fetchers\n\n let fetchControllers = new Map(); // Track loads based on the order in which they started\n\n let incrementingLoadId = 0; // 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\n let pendingNavigationLoadId = -1; // Fetchers that triggered data reloads as a result of their actions\n\n let fetchReloadIds = new Map(); // Fetchers that triggered redirect navigations from their actions\n\n let fetchRedirectIds = new Set(); // Most recent href/match for fetcher.load calls for fetchers\n\n let fetchLoadMatches = new Map(); // 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\n let activeDeferreds = new Map(); // 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\n let blockerFunctions = new Map(); // 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\n let ignoreNextHistoryUpdate = false; // 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\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\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\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\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); // Put the blocker into a blocked state\n\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n\n proceed() {\n updateBlocker(blockerKey, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location\n }); // Re-do the same POP navigation we just blocked\n\n init.history.go(delta);\n },\n\n reset() {\n deleteBlocker(blockerKey);\n updateState({\n blockers: new Map(router.state.blockers)\n });\n }\n\n });\n return;\n }\n\n return startNavigation(historyAction, location);\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\n if (!state.initialized) {\n startNavigation(Action.Pop, state.location);\n }\n\n return router;\n } // Clean up a router and it's side effects\n\n\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n } // Subscribe to state updates for the router\n\n\n function subscribe(fn) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n } // Update our state and notify the calling context of the change\n\n\n function updateState(newState) {\n state = _extends({}, state, newState);\n subscribers.forEach(subscriber => subscriber(state));\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\n\n function completeNavigation(location, newState) {\n var _location$state, _location$state2;\n\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\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 } // Always preserve any existing loaderData from re-used routes\n\n\n let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData; // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n\n for (let [key] of blockerFunctions) {\n deleteBlocker(key);\n } // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n\n\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\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\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: new Map(state.blockers)\n }));\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 } // Reset stateful navigation vars\n\n\n pendingAction = Action.Pop;\n pendingPreventScrollReset = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\n } // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n\n\n async function navigate(to, opts) {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let {\n path,\n submission,\n error\n } = normalizeNavigateOptions(to, future, opts);\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state); // 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\n nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n let historyAction = Action.Push;\n\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\n let preventScrollReset = opts && \"preventScrollReset\" in opts ? opts.preventScrollReset === true : undefined;\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n\n proceed() {\n updateBlocker(blockerKey, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation\n }); // Send the same navigation through\n\n navigate(to, opts);\n },\n\n reset() {\n deleteBlocker(blockerKey);\n updateState({\n blockers: new Map(state.blockers)\n });\n }\n\n });\n return;\n }\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 });\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\n\n function revalidate() {\n interruptActiveLoads();\n updateState({\n revalidation: \"loading\"\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\n if (state.navigation.state === \"submitting\") {\n return;\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\n\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true\n });\n return;\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\n\n startNavigation(pendingAction || state.historyAction, state.navigation.location, {\n overrideNavigation: state.navigation\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\n\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; // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, init.basename); // Short circuit with a 404 on the root error boundary if we match nothing\n\n if (!matches) {\n let error = getInternalRouterError(404, {\n pathname: location.pathname\n });\n let {\n matches: notFoundMatches,\n route\n } = getShortCircuitMatches(routesToUse); // Cancel all pending deferred on 404s since we don't keep any routes\n\n cancelActiveDeferreds();\n completeNavigation(location, {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error\n }\n });\n return;\n } // Short circuit if it's only a hash change and not a mutation submission\n // For example, on /page#hash and submit a <Form method=\"post\"> which will\n // default to a navigation to /page\n\n\n if (isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {\n completeNavigation(location, {\n matches\n });\n return;\n } // Create a controller/Request for this navigation\n\n\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);\n let pendingActionData;\n let pendingError;\n\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 pendingError = {\n [findNearestBoundary(matches).route.id]: opts.pendingError\n };\n } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {\n // Call action if we received an action submission\n let actionOutput = await handleAction(request, location, opts.submission, matches, {\n replace: opts.replace\n });\n\n if (actionOutput.shortCircuited) {\n return;\n }\n\n pendingActionData = actionOutput.pendingActionData;\n pendingError = actionOutput.pendingActionError;\n\n let navigation = _extends({\n state: \"loading\",\n location\n }, opts.submission);\n\n loadingNavigation = navigation; // Create a GET request for the loaders\n\n request = new Request(request.url, {\n signal: request.signal\n });\n } // Call loaders\n\n\n let {\n shortCircuited,\n loaderData,\n errors\n } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, pendingActionData, pendingError);\n\n if (shortCircuited) {\n return;\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\n\n pendingNavigationController = null;\n completeNavigation(location, _extends({\n matches\n }, pendingActionData ? {\n actionData: pendingActionData\n } : {}, {\n loaderData,\n errors\n }));\n } // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n\n\n async function handleAction(request, location, submission, matches, opts) {\n interruptActiveLoads(); // Put us in a submitting state\n\n let navigation = _extends({\n state: \"submitting\",\n location\n }, submission);\n\n updateState({\n navigation\n }); // Call our action and get the result\n\n let result;\n let actionMatch = getTargetMatch(matches, location);\n\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 result = await callLoaderOrAction(\"action\", request, actionMatch, matches, manifest, detectErrorBoundary, router.basename);\n\n if (request.signal.aborted) {\n return {\n shortCircuited: true\n };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace;\n\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 replace = result.location === state.location.pathname + state.location.search;\n }\n\n await startRedirectNavigation(state, result, {\n submission,\n replace\n });\n return {\n shortCircuited: true\n };\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); // By default, all submissions are REPLACE navigations, but if the\n // action threw an error that'll be rendered in an errorElement, we fall\n // back to PUSH so that the user can use the back button to get back to\n // the pre-submission form location to try again\n\n if ((opts && opts.replace) !== true) {\n pendingAction = Action.Push;\n }\n\n return {\n // Send back an empty object we can use to clear out any prior actionData\n pendingActionData: {},\n pendingActionError: {\n [boundaryMatch.route.id]: result.error\n }\n };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, {\n type: \"defer-action\"\n });\n }\n\n return {\n pendingActionData: {\n [actionMatch.route.id]: result.data\n }\n };\n } // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n\n\n async function handleLoaders(request, location, matches, overrideNavigation, submission, fetcherSubmission, replace, pendingActionData, pendingError) {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation = overrideNavigation;\n\n if (!loadingNavigation) {\n let navigation = _extends({\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined\n }, submission);\n\n loadingNavigation = navigation;\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\n\n let activeSubmission = submission || fetcherSubmission ? submission || fetcherSubmission : loadingNavigation.formMethod && loadingNavigation.formAction && loadingNavigation.formData && loadingNavigation.formEncType ? {\n formMethod: loadingNavigation.formMethod,\n formAction: loadingNavigation.formAction,\n formData: loadingNavigation.formData,\n formEncType: loadingNavigation.formEncType\n } : undefined;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, fetchLoadMatches, routesToUse, init.basename, pendingActionData, pendingError); // 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\n cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId)); // Short circuit if we have no loaders to run\n\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n completeNavigation(location, _extends({\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors: pendingError || null\n }, pendingActionData ? {\n actionData: pendingActionData\n } : {}));\n return {\n shortCircuited: true\n };\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\n\n if (!isUninterruptedRevalidation) {\n revalidatingFetchers.forEach(rf => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = {\n state: \"loading\",\n data: fetcher && fetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n \" _hasFetcherDoneAnything \": true\n };\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n let actionData = pendingActionData || state.actionData;\n updateState(_extends({\n navigation: loadingNavigation\n }, actionData ? Object.keys(actionData).length === 0 ? {\n actionData: null\n } : {\n actionData\n } : {}, revalidatingFetchers.length > 0 ? {\n fetchers: new Map(state.fetchers)\n } : {}));\n }\n\n pendingNavigationLoadId = ++incrementingLoadId;\n revalidatingFetchers.forEach(rf => fetchControllers.set(rf.key, pendingNavigationController));\n let {\n results,\n loaderResults,\n fetcherResults\n } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request);\n\n if (request.signal.aborted) {\n return {\n shortCircuited: true\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\n\n revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key)); // If any loaders returned a redirect Response, start a new REPLACE navigation\n\n let redirect = findRedirect(results);\n\n if (redirect) {\n await startRedirectNavigation(state, redirect, {\n replace\n });\n return {\n shortCircuited: true\n };\n } // Process and commit output from loaders\n\n\n let {\n loaderData,\n errors\n } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds); // Wire up subscribers to update loaderData as promises settle\n\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 markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n return _extends({\n loaderData,\n errors\n }, didAbortFetchLoads || revalidatingFetchers.length > 0 ? {\n fetchers: new Map(state.fetchers)\n } : {});\n }\n\n function getFetcher(key) {\n return state.fetchers.get(key) || IDLE_FETCHER;\n } // Trigger a fetcher load/submit for the given fetcher key\n\n\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\n if (fetchControllers.has(key)) abortFetcher(key);\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches = matchRoutes(routesToUse, href, init.basename);\n\n if (!matches) {\n setFetcherError(key, routeId, getInternalRouterError(404, {\n pathname: href\n }));\n return;\n }\n\n let {\n path,\n submission\n } = normalizeNavigateOptions(href, future, opts, true);\n let match = getTargetMatch(matches, path);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(key, routeId, path, match, matches, submission);\n return;\n } // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n\n\n fetchLoadMatches.set(key, {\n routeId,\n path\n });\n handleFetcherLoader(key, routeId, path, match, matches, submission);\n } // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n\n\n async function handleFetcherAction(key, routeId, path, match, requestMatches, submission) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId\n });\n setFetcherError(key, routeId, error);\n return;\n } // Put this fetcher into it's submitting state\n\n\n let existingFetcher = state.fetchers.get(key);\n\n let fetcher = _extends({\n state: \"submitting\"\n }, submission, {\n data: existingFetcher && existingFetcher.data,\n \" _hasFetcherDoneAnything \": true\n });\n\n state.fetchers.set(key, fetcher);\n updateState({\n fetchers: new Map(state.fetchers)\n }); // Call the action for the fetcher\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);\n fetchControllers.set(key, abortController);\n let actionResult = await callLoaderOrAction(\"action\", fetchRequest, match, requestMatches, manifest, detectErrorBoundary, router.basename);\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by ou 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\n return;\n }\n\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n fetchRedirectIds.add(key);\n\n let loadingFetcher = _extends({\n state: \"loading\"\n }, submission, {\n data: undefined,\n \" _hasFetcherDoneAnything \": true\n });\n\n state.fetchers.set(key, loadingFetcher);\n updateState({\n fetchers: new Map(state.fetchers)\n });\n return startRedirectNavigation(state, actionResult, {\n submission,\n isFetchActionRedirect: true\n });\n } // Process any non-redirect errors thrown\n\n\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 } // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n\n\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, init.basename) : state.matches;\n invariant(matches, \"Didn't find any matches after fetcher action\");\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = _extends({\n state: \"loading\",\n data: actionResult.data\n }, submission, {\n \" _hasFetcherDoneAnything \": true\n });\n\n state.fetchers.set(key, loadFetcher);\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, fetchLoadMatches, routesToUse, init.basename, {\n [match.route.id]: actionResult.data\n }, undefined // No need to send through errors since we short circuit above\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\n revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = {\n state: \"loading\",\n data: existingFetcher && existingFetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n \" _hasFetcherDoneAnything \": true\n };\n state.fetchers.set(staleKey, revalidatingFetcher);\n fetchControllers.set(staleKey, abortController);\n });\n updateState({\n fetchers: new Map(state.fetchers)\n });\n let {\n results,\n loaderResults,\n fetcherResults\n } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);\n\n if (abortController.signal.aborted) {\n return;\n }\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach(r => fetchControllers.delete(r.key));\n let redirect = findRedirect(results);\n\n if (redirect) {\n return startRedirectNavigation(state, redirect);\n } // Process and commit output from loaders\n\n\n let {\n loaderData,\n errors\n } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);\n let doneFetcher = {\n state: \"idle\",\n data: actionResult.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n \" _hasFetcherDoneAnything \": true\n };\n state.fetchers.set(key, doneFetcher);\n let didAbortFetchLoads = abortStaleFetchLoads(loadId); // 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\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(_extends({\n errors,\n loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors)\n }, didAbortFetchLoads ? {\n fetchers: new Map(state.fetchers)\n } : {}));\n isRevalidationRequired = false;\n }\n } // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n\n\n async function handleFetcherLoader(key, routeId, path, match, matches, submission) {\n let existingFetcher = state.fetchers.get(key); // Put this fetcher into it's loading state\n\n let loadingFetcher = _extends({\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined\n }, submission, {\n data: existingFetcher && existingFetcher.data,\n \" _hasFetcherDoneAnything \": true\n });\n\n state.fetchers.set(key, loadingFetcher);\n updateState({\n fetchers: new Map(state.fetchers)\n }); // Call the loader for this fetcher route match\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);\n fetchControllers.set(key, abortController);\n let result = await callLoaderOrAction(\"loader\", fetchRequest, match, matches, manifest, detectErrorBoundary, router.basename); // 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\n if (isDeferredResult(result)) {\n result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;\n } // We can delete this so long as we weren't aborted by ou our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n\n\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n } // If the loader threw a redirect Response, start a new REPLACE navigation\n\n\n if (isRedirectResult(result)) {\n await startRedirectNavigation(state, result);\n return;\n } // Process any non-redirect errors thrown\n\n\n if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n state.fetchers.delete(key); // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch -\n // do we need to behave any differently with our non-redirect errors?\n // What if it was a non-redirect Response?\n\n updateState({\n fetchers: new Map(state.fetchers),\n errors: {\n [boundaryMatch.route.id]: result.error\n }\n });\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\"); // Put the fetcher back into an idle state\n\n let doneFetcher = {\n state: \"idle\",\n data: result.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n \" _hasFetcherDoneAnything \": true\n };\n state.fetchers.set(key, doneFetcher);\n updateState({\n fetchers: new Map(state.fetchers)\n });\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\n\n async function startRedirectNavigation(state, redirect, _temp) {\n var _window;\n\n let {\n submission,\n replace,\n isFetchActionRedirect\n } = _temp === void 0 ? {} : _temp;\n\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n\n let redirectLocation = createLocation(state.location, redirect.location, // TODO: This can be removed once we get rid of useTransition in Remix v2\n _extends({\n _isRedirect: true\n }, isFetchActionRedirect ? {\n _isFetchActionRedirect: true\n } : {}));\n invariant(redirectLocation, \"Expected a location on the redirect navigation\"); // Check if this an absolute external redirect that goes to a new origin\n\n if (ABSOLUTE_URL_REGEX.test(redirect.location) && isBrowser && typeof ((_window = window) == null ? void 0 : _window.location) !== \"undefined\") {\n let url = init.history.createURL(redirect.location);\n let isDifferentBasename = stripBasename(url.pathname, init.basename || \"/\") == null;\n\n if (window.location.origin !== url.origin || isDifferentBasename) {\n if (replace) {\n window.location.replace(redirect.location);\n } else {\n window.location.assign(redirect.location);\n }\n\n return;\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\n\n pendingNavigationController = null;\n let redirectHistoryAction = replace === true ? Action.Replace : Action.Push; // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n\n let {\n formMethod,\n formAction,\n formEncType,\n formData\n } = state.navigation;\n\n if (!submission && formMethod && formAction && formData && formEncType) {\n submission = {\n formMethod,\n formAction,\n formEncType,\n formData\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\n\n if (redirectPreserveMethodStatusCodes.has(redirect.status) && submission && isMutationMethod(submission.formMethod)) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: _extends({}, submission, {\n formAction: redirect.location\n }),\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset\n });\n } else if (isFetchActionRedirect) {\n // For a fetch action redirect, we kick off a new loading navigation\n // without the fetcher submission, but we send it along for shouldRevalidate\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation: {\n state: \"loading\",\n location: redirectLocation,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined\n },\n fetcherSubmission: submission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset\n });\n } else {\n // Otherwise, we kick off a new loading navigation, preserving the\n // submission info for the duration of this navigation\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation: {\n state: \"loading\",\n location: redirectLocation,\n formMethod: submission ? submission.formMethod : undefined,\n formAction: submission ? submission.formAction : undefined,\n formEncType: submission ? submission.formEncType : undefined,\n formData: submission ? submission.formData : undefined\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset\n });\n }\n }\n\n async function callLoadersAndMaybeResolveData(currentMatches, matches, matchesToLoad, fetchersToLoad, request) {\n // Call all navigation loaders and revalidating fetcher loaders in parallel,\n // then slice off the results into separate arrays so we can handle them\n // accordingly\n let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction(\"loader\", request, match, matches, manifest, detectErrorBoundary, router.basename)), ...fetchersToLoad.map(f => {\n if (f.matches && f.match) {\n return callLoaderOrAction(\"loader\", createClientSideRequest(init.history, f.path, request.signal), f.match, f.matches, manifest, detectErrorBoundary, router.basename);\n } else {\n let error = {\n type: ResultType.error,\n error: getInternalRouterError(404, {\n pathname: f.path\n })\n };\n return error;\n }\n })]);\n let loaderResults = results.slice(0, matchesToLoad.length);\n let fetcherResults = results.slice(matchesToLoad.length);\n await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, request.signal, false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(f => f.match), fetcherResults, request.signal, true)]);\n return {\n results,\n loaderResults,\n fetcherResults\n };\n }\n\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true; // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n\n cancelledDeferredRoutes.push(...cancelActiveDeferreds()); // Abort in-flight fetcher loads\n\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.push(key);\n abortFetcher(key);\n }\n });\n }\n\n function setFetcherError(key, routeId, error) {\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 }\n\n function deleteFetcher(key) {\n if (fetchControllers.has(key)) abortFetcher(key);\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n state.fetchers.delete(key);\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\n function markFetchersDone(keys) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = {\n state: \"idle\",\n data: fetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n \" _hasFetcherDoneAnything \": true\n };\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone() {\n let doneKeys = [];\n\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, \"Expected fetcher: \" + key);\n\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n }\n }\n\n markFetchersDone(doneKeys);\n }\n\n function abortStaleFetchLoads(landedId) {\n let yeetedKeys = [];\n\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\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key, fn) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n } // Utility function to update blockers, ensuring valid state transitions\n\n\n function updateBlocker(key, newBlocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER; // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n\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 state.blockers.set(key, newBlocker);\n updateState({\n blockers: new Map(state.blockers)\n });\n }\n\n function shouldBlockNavigation(_ref2) {\n let {\n currentLocation,\n nextLocation,\n historyAction\n } = _ref2;\n\n if (blockerFunctions.size === 0) {\n return;\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\n\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\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 } // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n\n\n if (blockerFunction({\n currentLocation,\n nextLocation,\n historyAction\n })) {\n return blockerKey;\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 } // Opt in to capturing and reporting scroll positions during navigations,\n // used by the <ScrollRestoration> component\n\n\n function enableScrollRestoration(positions, getPosition, getKey) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n\n getScrollRestorationKey = getKey || (location => location.key); // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n // and therefore have no savedScrollPositions available\n\n\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n\n if (y != null) {\n updateState({\n restoreScrollPosition: y\n });\n }\n }\n\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n\n function saveScrollPosition(location, matches) {\n if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData));\n let key = getScrollRestorationKey(location, userMatches) || location.key;\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(location, matches) {\n if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData));\n let key = getScrollRestorationKey(location, userMatches) || location.key;\n let y = savedScrollPositions[key];\n\n if (typeof y === \"number\") {\n return y;\n }\n }\n\n return null;\n }\n\n function _internalSetRoutes(newRoutes) {\n inFlightDataRoutes = newRoutes;\n }\n\n router = {\n get basename() {\n return init.basename;\n },\n\n get state() {\n return state;\n },\n\n get routes() {\n return dataRoutes;\n },\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,\n dispose,\n getBlocker,\n deleteBlocker,\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} //#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\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 detectErrorBoundary = (opts == null ? void 0 : opts.detectErrorBoundary) || defaultDetectErrorBoundary;\n let dataRoutes = convertRoutesToDataRoutes(routes, detectErrorBoundary, undefined, manifest);\n let basename = (opts ? opts.basename : null) || \"/\";\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\n async function query(request, _temp2) {\n let {\n requestContext\n } = _temp2 === void 0 ? {} : _temp2;\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); // SSR supports HEAD requests while SPA doesn't\n\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\n let result = await queryImpl(request, location, matches, requestContext);\n\n if (isResponse(result)) {\n return result;\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\n\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\n\n async function queryRoute(request, _temp3) {\n let {\n routeId,\n requestContext\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); // SSR supports HEAD requests while SPA doesn't\n\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\n let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location);\n\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\n let result = await queryImpl(request, location, matches, requestContext, match);\n\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n\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 } // Pick off the right state value to return\n\n\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n var _result$activeDeferre;\n\n let data = Object.values(result.loaderData)[0];\n\n if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(request, location, matches, requestContext, routeMatch) {\n invariant(request.signal, \"query()/queryRoute() requests must contain an AbortController signal\");\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, routeMatch != null);\n return result;\n }\n\n let result = await loadRouteData(request, matches, requestContext, 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, we throw\n // it to bail out and then return or throw here based on whether the user\n // returned or threw\n if (isQueryRouteResponse(e)) {\n if (e.type === ResultType.error && !isRedirectResponse(e.response)) {\n throw e.response;\n }\n\n return e.response;\n } // Redirects are always returned since they don't propagate to catch\n // boundaries\n\n\n if (isRedirectResponse(e)) {\n return e;\n }\n\n throw e;\n }\n }\n\n async function submit(request, matches, actionMatch, requestContext, isRouteRequest) {\n let result;\n\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\n if (isRouteRequest) {\n throw error;\n }\n\n result = {\n type: ResultType.error,\n error\n };\n } else {\n result = await callLoaderOrAction(\"action\", request, actionMatch, matches, manifest, detectErrorBoundary, basename, true, isRouteRequest, requestContext);\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(method + \"() call aborted\");\n }\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.status,\n headers: {\n Location: result.location\n }\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, {\n type: \"defer-action\"\n });\n\n if (isRouteRequest) {\n throw error;\n }\n\n result = {\n type: ResultType.error,\n error\n };\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\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\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 let context = await loadRouteData(request, matches, requestContext, undefined, {\n [boundaryMatch.route.id]: result.error\n }); // action status codes take precedence over loader status codes\n\n return _extends({}, context, {\n statusCode: isRouteErrorResponse(result.error) ? result.error.status : 500,\n actionData: null,\n actionHeaders: _extends({}, result.headers ? {\n [actionMatch.route.id]: result.headers\n } : {})\n });\n } // Create a GET request for the loaders\n\n\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal\n });\n let context = await loadRouteData(loaderRequest, matches, requestContext);\n return _extends({}, context, result.statusCode ? {\n statusCode: result.statusCode\n } : {}, {\n actionData: {\n [actionMatch.route.id]: result.data\n },\n actionHeaders: _extends({}, result.headers ? {\n [actionMatch.route.id]: result.headers\n } : {})\n });\n }\n\n async function loadRouteData(request, matches, requestContext, routeMatch, pendingActionError) {\n let isRouteRequest = routeMatch != null; // Short circuit if we have no loaders to run (queryRoute())\n\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\n let requestMatches = routeMatch ? [routeMatch] : getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]);\n let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy); // Short circuit if we have no loaders to run (query())\n\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: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null\n };\n }\n\n let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction(\"loader\", request, match, matches, manifest, detectErrorBoundary, basename, true, isRouteRequest, requestContext))]);\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(method + \"() call aborted\");\n } // Process and commit output from loaders\n\n\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError, activeDeferreds); // Add a null for any non-loader matches for proper revalidation on the client\n\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\n return {\n dataRoutes,\n query,\n queryRoute\n };\n} //#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\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 */\n\nfunction getStaticContextFromError(routes, context, error) {\n let newContext = _extends({}, context, {\n statusCode: 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error\n }\n });\n\n return newContext;\n}\n\nfunction isSubmissionNavigation(opts) {\n return opts != null && \"formData\" in opts;\n} // Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\n\n\nfunction normalizeNavigateOptions(to, future, opts, isFetcher) {\n if (isFetcher === void 0) {\n isFetcher = false;\n }\n\n let path = typeof to === \"string\" ? to : createPath(to); // Return location verbatim on non-submission navigations\n\n if (!opts || !isSubmissionNavigation(opts)) {\n return {\n path\n };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, {\n method: opts.formMethod\n })\n };\n } // Create a Submission on non-GET navigations\n\n\n let submission;\n\n if (opts.formData) {\n let formMethod = opts.formMethod || \"get\";\n submission = {\n formMethod: future.v7_normalizeFormMethod ? formMethod.toUpperCase() : formMethod.toLowerCase(),\n formAction: stripHashFromPath(path),\n formEncType: opts && opts.formEncType || \"application/x-www-form-urlencoded\",\n formData: opts.formData\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return {\n path,\n submission\n };\n }\n } // Flatten submission onto URLSearchParams for GET submissions\n\n\n let parsedPath = parsePath(path);\n let searchParams = convertFormDataToSearchParams(opts.formData); // Since fetcher GET submissions only run a single loader (as opposed to\n // navigation GET submissions which run all loaders), we need to preserve\n // any incoming ?index params\n\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n\n parsedPath.search = \"?\" + searchParams;\n return {\n path: createPath(parsedPath),\n submission\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\n\n\nfunction getLoaderMatchesUntilBoundary(matches, boundaryId) {\n let boundaryMatches = matches;\n\n if (boundaryId) {\n let index = matches.findIndex(m => m.route.id === boundaryId);\n\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n\n return boundaryMatches;\n}\n\nfunction getMatchesToLoad(history, state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, fetchLoadMatches, routesToUse, basename, pendingActionData, pendingError) {\n let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : undefined;\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n let defaultShouldRevalidate = // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate\n isRevalidationRequired || // Clicked the same link, resubmitted a GET form\n currentUrl.toString() === nextUrl.toString() || // Search params affect all loaders\n currentUrl.search !== nextUrl.search; // Pick navigation matches that are net-new or qualify for revalidation\n\n let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n let navigationMatches = boundaryMatches.filter((match, index) => {\n if (match.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\n if (match.route.loader == null) {\n return false;\n } // Always call the loader on new route instances and pending defer cancellations\n\n\n if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) {\n return true;\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\n\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 defaultShouldRevalidate: defaultShouldRevalidate || isNewRouteInstance(currentRouteMatch, nextRouteMatch)\n }));\n }); // Pick fetcher.loads that need to be revalidated\n\n let revalidatingFetchers = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate if fetcher won't be present in the subsequent render\n if (!matches.some(m => m.route.id === f.routeId)) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename); // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData\n\n if (!fetcherMatches) {\n revalidatingFetchers.push(_extends({\n key\n }, f, {\n matches: null,\n match: null\n }));\n return;\n }\n\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n if (cancelledFetcherLoads.includes(key)) {\n revalidatingFetchers.push(_extends({\n key,\n matches: fetcherMatches,\n match: fetcherMatch\n }, f));\n return;\n } // Revalidating fetchers are decoupled from the route matches since they\n // hit a static href, so they _always_ check shouldRevalidate and the\n // default is strictly if a revalidation is explicitly required (action\n // submissions, useRevalidator, X-Remix-Revalidate).\n\n\n let 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 defaultShouldRevalidate\n }));\n\n if (shouldRevalidate) {\n revalidatingFetchers.push(_extends({\n key,\n matches: fetcherMatches,\n match: fetcherMatch\n }, f));\n }\n });\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction isNewLoader(currentLoaderData, currentMatch, match) {\n let isNew = // [a] -> [a, b]\n !currentMatch || // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id; // 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\n let isMissingData = currentLoaderData[match.route.id] === undefined; // Always load if this is a net-new route or we don't yet have data\n\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(currentMatch, match) {\n let currentPath = currentMatch.route.path;\n return (// param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname || // 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}\n\nfunction shouldRevalidateLoader(loaderMatch, arg) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\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 */\n\n\nasync function loadLazyRouteModule(route, detectErrorBoundary, manifest) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy(); // 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\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\"); // 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\n let routeUpdates = {};\n\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue = routeToUpdate[lazyRouteProperty];\n let isPropertyStaticallyDefined = staticRouteValue !== undefined && // 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\n if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {\n routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];\n }\n } // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to detectErrorBoundary\n\n\n Object.assign(routeToUpdate, routeUpdates); // 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\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `detectErrorBoundary` function to set the `hasErrorBoundary` route\n // property since the logic will differ between frameworks.\n hasErrorBoundary: detectErrorBoundary(_extends({}, routeToUpdate)),\n lazy: undefined\n });\n}\n\nasync function callLoaderOrAction(type, request, match, matches, manifest, detectErrorBoundary, basename, isStaticRequest, isRouteRequest, requestContext) {\n if (basename === void 0) {\n basename = \"/\";\n }\n\n if (isStaticRequest === void 0) {\n isStaticRequest = false;\n }\n\n if (isRouteRequest === void 0) {\n isRouteRequest = false;\n }\n\n let resultType;\n let result;\n let onReject;\n\n let runHandler = handler => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject;\n let abortPromise = new Promise((_, r) => reject = r);\n\n onReject = () => reject();\n\n request.signal.addEventListener(\"abort\", onReject);\n return Promise.race([handler({\n request,\n params: match.params,\n context: requestContext\n }), abortPromise]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let values = await Promise.all([runHandler(handler), loadLazyRouteModule(match.route, detectErrorBoundary, manifest)]);\n result = values[0];\n } else {\n // Load lazy route module, then run any returned handler\n await loadLazyRouteModule(match.route, detectErrorBoundary, manifest);\n handler = match.route[type];\n\n if (handler) {\n // Handler still run 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 throw getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).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 data: undefined\n };\n }\n }\n } else {\n invariant(handler, \"Could not find the \" + type + \" to run on the \\\"\" + match.route.id + \"\\\" route\");\n result = await runHandler(handler);\n }\n\n invariant(result !== undefined, \"You defined \" + (type === \"action\" ? \"an action\" : \"a loader\") + \" for route \" + (\"\\\"\" + match.route.id + \"\\\" but didn't return anything from your `\" + type + \"` \") + \"function. Please return a value or `null`.\");\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n if (isResponse(result)) {\n let status = result.status; // Process redirects\n\n if (redirectStatusCodes.has(status)) {\n let location = result.headers.get(\"Location\");\n invariant(location, \"Redirects returned/thrown from loaders/actions must have a Location header\"); // Support relative routing in internal redirects\n\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n let activeMatches = matches.slice(0, matches.indexOf(match) + 1);\n let routePathnames = getPathContributingMatches(activeMatches).map(match => match.pathnameBase);\n let resolvedLocation = resolveTo(location, routePathnames, new URL(request.url).pathname);\n invariant(createPath(resolvedLocation), \"Unable to resolve redirect location: \" + location); // Prepend the basename to the redirect location if we have one\n\n if (basename) {\n let path = resolvedLocation.pathname;\n resolvedLocation.pathname = path === \"/\" ? basename : joinPaths([basename, path]);\n }\n\n location = createPath(resolvedLocation);\n } else if (!isStaticRequest) {\n // Strip off the protocol+origin for same-origin + same-basename absolute\n // redirects. If this is a static request, we can let it go back to the\n // browser as-is\n let currentUrl = new URL(request.url);\n let url = location.startsWith(\"//\") ? new URL(currentUrl.protocol + location) : new URL(location);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n\n if (url.origin === currentUrl.origin && isSameBasename) {\n location = url.pathname + url.search + url.hash;\n }\n } // Don't process redirects in the router during static requests requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect. We also update the Location header in place in this flow so\n // basename and relative routing is taken into account\n\n\n if (isStaticRequest) {\n result.headers.set(\"Location\", location);\n throw result;\n }\n\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null\n };\n } // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping. We do this with the QueryRouteResponse wrapper\n // interface so we can know whether it was returned or thrown\n\n\n if (isRouteRequest) {\n // eslint-disable-next-line no-throw-literal\n throw {\n type: resultType || ResultType.data,\n response: result\n };\n }\n\n let data;\n let contentType = result.headers.get(\"Content-Type\"); // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n data = await result.json();\n } else {\n data = await result.text();\n }\n\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: new ErrorResponse(status, result.statusText, data),\n headers: result.headers\n };\n }\n\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers\n };\n }\n\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: result\n };\n }\n\n if (isDeferredData(result)) {\n var _result$init, _result$init2;\n\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\n return {\n type: ResultType.data,\n data: result\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)\n\n\nfunction createClientSideRequest(history, location, signal, submission) {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init = {\n signal\n };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let {\n formMethod,\n formEncType,\n formData\n } = submission; // 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\n init.method = formMethod.toUpperCase();\n init.body = formEncType === \"application/x-www-form-urlencoded\" ? convertFormDataToSearchParams(formData) : formData;\n } // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData) {\n let searchParams = new URLSearchParams();\n\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, value instanceof File ? value.name : value);\n }\n\n return searchParams;\n}\n\nfunction processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds) {\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 = {}; // Process loader results into state.loaderData/state.errors\n\n results.forEach((result, index) => {\n let id = matchesToLoad[index].route.id;\n invariant(!isRedirectResult(result), \"Cannot handle redirect results in processLoaderData\");\n\n if (isErrorResult(result)) {\n // Look upwards from the matched route for the closest ancestor\n // error boundary, defaulting to the root match\n let boundaryMatch = findNearestBoundary(matches, id);\n let error = result.error; // 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\n if (pendingError) {\n error = Object.values(pendingError)[0];\n pendingError = undefined;\n }\n\n errors = errors || {}; // Prefer higher error values if lower errors bubble to the same boundary\n\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n } // Clear our any prior loaderData for the throwing route\n\n\n loaderData[id] = undefined; // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;\n }\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 } 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\n\n if (result.statusCode != null && result.statusCode !== 200 && !foundError) {\n statusCode = result.statusCode;\n }\n\n if (result.headers) {\n loaderHeaders[id] = result.headers;\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\n if (pendingError) {\n errors = pendingError;\n loaderData[Object.keys(pendingError)[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders\n };\n}\n\nfunction processLoaderData(state, matches, matchesToLoad, results, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds) {\n let {\n loaderData,\n errors\n } = processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds); // Process results from our revalidating fetchers\n\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let {\n key,\n match\n } = revalidatingFetchers[index];\n invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, \"Did not find corresponding fetcher result\");\n let result = fetcherResults[index]; // Process fetcher non-redirect errors\n\n if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id);\n\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = _extends({}, errors, {\n [boundaryMatch.route.id]: result.error\n });\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 = {\n state: \"idle\",\n data: result.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n \" _hasFetcherDoneAnything \": true\n };\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n return {\n loaderData,\n errors\n };\n}\n\nfunction mergeLoaderData(loaderData, newLoaderData, matches, errors) {\n let mergedLoaderData = _extends({}, newLoaderData);\n\n for (let match of matches) {\n let id = match.route.id;\n\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\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n\n return mergedLoaderData;\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\n\n\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}\n\nfunction getShortCircuitMatches(routes) {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route = 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}\n\nfunction getInternalRouterError(status, _temp4) {\n let {\n pathname,\n routeId,\n method,\n type\n } = _temp4 === void 0 ? {} : _temp4;\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n\n 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 }\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\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\n return new ErrorResponse(status || 500, statusText, new Error(errorMessage), true);\n} // Find any returned redirect errors, starting from the lowest match\n\n\nfunction findRedirect(results) {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n\n if (isRedirectResult(result)) {\n return result;\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}\n\nfunction isHashChangeOnly(a, b) {\n return a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash;\n}\n\nfunction isDeferredResult(result) {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result) {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result) {\n return (result && result.type) === ResultType.redirect;\n}\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}\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}\n\nfunction isRedirectResponse(result) {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isQueryRouteResponse(obj) {\n return obj && isResponse(obj.response) && (obj.type === ResultType.data || ResultType.error);\n}\n\nfunction isValidMethod(method) {\n return validRequestMethods.has(method.toLowerCase());\n}\n\nfunction isMutationMethod(method) {\n return validMutationMethods.has(method.toLowerCase());\n}\n\nasync function resolveDeferredResults(currentMatches, matchesToLoad, results, signal, isFetcher, currentLoaderData) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index]; // 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\n if (!match) {\n continue;\n }\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\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 await resolveDeferredData(result, signal, isFetcher).then(result => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\n\nasync function resolveDeferredData(result, signal, unwrap) {\n if (unwrap === void 0) {\n unwrap = false;\n }\n\n let aborted = await result.deferredData.resolveData(signal);\n\n if (aborted) {\n return;\n }\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\n return {\n type: ResultType.data,\n data: result.deferredData.data\n };\n}\n\nfunction hasNakedIndexQuery(search) {\n return new URLSearchParams(search).getAll(\"index\").some(v => v === \"\");\n} // Note: This should match the format exported by useMatches, so if you change\n// this please also change that :) Eventually we'll DRY this up\n\n\nfunction createUseMatchesMatch(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}\n\nfunction getTargetMatch(matches, location) {\n let search = typeof location === \"string\" ? parsePath(location).search : location.search;\n\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 } // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n\n\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n} //#endregion\n\nexport { AbortedDeferredError, Action, ErrorResponse, IDLE_BLOCKER, IDLE_FETCHER, IDLE_NAVIGATION, UNSAFE_DEFERRED_SYMBOL, DeferredData as UNSAFE_DeferredData, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, getPathContributingMatches as UNSAFE_getPathContributingMatches, 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, resolvePath, resolveTo, stripBasename };\n//# sourceMappingURL=router.js.map\n","/**\n * React Router v6.10.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 { UNSAFE_invariant, joinPaths, matchPath, UNSAFE_getPathContributingMatches, UNSAFE_warning, resolveTo, parsePath, matchRoutes, Action, isRouteErrorResponse, createMemoryHistory, stripBasename, AbortedDeferredError, createRouter } from '@remix-run/router';\nexport { AbortedDeferredError, Action as NavigationType, createPath, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, resolvePath } from '@remix-run/router';\nimport * as React from 'react';\n\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 * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\n\nfunction isPolyfill(x, y) {\n return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n ;\n}\n\nconst is = typeof Object.is === \"function\" ? Object.is : isPolyfill; // Intentionally not using named imports because Rollup uses dynamic\n// dispatch for CommonJS interop named imports.\n\nconst {\n useState,\n useEffect,\n useLayoutEffect,\n useDebugValue\n} = React;\nlet didWarnOld18Alpha = false;\nlet didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works\n// because of a very particular set of implementation details and assumptions\n// -- change any one of them and it will break. The most important assumption\n// is that updates are always synchronous, because concurrent rendering is\n// only available in versions of React that also have a built-in\n// useSyncExternalStore API. And we only use this shim when the built-in API\n// does not exist.\n//\n// Do not assume that the clever hacks used by this hook also work in general.\n// The point of this shim is to replace the need for hacks by other libraries.\n\nfunction useSyncExternalStore$2(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of\n// React do not expose a way to check if we're hydrating. So users of the shim\n// will need to track that themselves and return the correct value\n// from `getSnapshot`.\ngetServerSnapshot) {\n if (process.env.NODE_ENV !== \"production\") {\n if (!didWarnOld18Alpha) {\n if (\"startTransition\" in React) {\n didWarnOld18Alpha = true;\n console.error(\"You are using an outdated, pre-release alpha of React 18 that \" + \"does not support useSyncExternalStore. The \" + \"use-sync-external-store shim will not work correctly. Upgrade \" + \"to a newer pre-release.\");\n }\n }\n } // Read the current snapshot from the store on every render. Again, this\n // breaks the rules of React, and only works here because of specific\n // implementation details, most importantly that updates are\n // always synchronous.\n\n\n const value = getSnapshot();\n\n if (process.env.NODE_ENV !== \"production\") {\n if (!didWarnUncachedGetSnapshot) {\n const cachedValue = getSnapshot();\n\n if (!is(value, cachedValue)) {\n console.error(\"The result of getSnapshot should be cached to avoid an infinite loop\");\n didWarnUncachedGetSnapshot = true;\n }\n }\n } // Because updates are synchronous, we don't queue them. Instead we force a\n // re-render whenever the subscribed state changes by updating an some\n // arbitrary useState hook. Then, during render, we call getSnapshot to read\n // the current value.\n //\n // Because we don't actually use the state returned by the useState hook, we\n // can save a bit of memory by storing other stuff in that slot.\n //\n // To implement the early bailout, we need to track some things on a mutable\n // object. Usually, we would put that in a useRef hook, but we can stash it in\n // our useState hook instead.\n //\n // To force a re-render, we call forceUpdate({inst}). That works because the\n // new object always fails an equality check.\n\n\n const [{\n inst\n }, forceUpdate] = useState({\n inst: {\n value,\n getSnapshot\n }\n }); // Track the latest getSnapshot function with a ref. This needs to be updated\n // in the layout phase so we can access it during the tearing check that\n // happens on subscribe.\n\n useLayoutEffect(() => {\n inst.value = value;\n inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the\n // commit phase if there was an interleaved mutation. In concurrent mode\n // this can happen all the time, but even in synchronous mode, an earlier\n // effect may have mutated the store.\n\n if (checkIfSnapshotChanged(inst)) {\n // Force a re-render.\n forceUpdate({\n inst\n });\n } // eslint-disable-next-line react-hooks/exhaustive-deps\n\n }, [subscribe, value, getSnapshot]);\n useEffect(() => {\n // Check for changes right before subscribing. Subsequent changes will be\n // detected in the subscription handler.\n if (checkIfSnapshotChanged(inst)) {\n // Force a re-render.\n forceUpdate({\n inst\n });\n }\n\n const handleStoreChange = () => {\n // TODO: Because there is no cross-renderer API for batching updates, it's\n // up to the consumer of this library to wrap their subscription event\n // with unstable_batchedUpdates. Should we try to detect when this isn't\n // the case and print a warning in development?\n // The store changed. Check if the snapshot changed since the last time we\n // read from the store.\n if (checkIfSnapshotChanged(inst)) {\n // Force a re-render.\n forceUpdate({\n inst\n });\n }\n }; // Subscribe to the store and return a clean-up function.\n\n\n return subscribe(handleStoreChange); // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [subscribe]);\n useDebugValue(value);\n return value;\n}\n\nfunction checkIfSnapshotChanged(inst) {\n const latestGetSnapshot = inst.getSnapshot;\n const prevValue = inst.value;\n\n try {\n const nextValue = latestGetSnapshot();\n return !is(prevValue, nextValue);\n } catch (error) {\n return true;\n }\n}\n\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 * @flow\n */\nfunction useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {\n // Note: The shim does not use getServerSnapshot, because pre-18 versions of\n // React do not expose a way to check if we're hydrating. So users of the shim\n // will need to track that themselves and return the correct value\n // from `getSnapshot`.\n return getSnapshot();\n}\n\n/**\n * Inlined into the react-router repo since use-sync-external-store does not\n * provide a UMD-compatible package, so we need this to be able to distribute\n * UMD react-router bundles\n */\nconst canUseDOM = !!(typeof window !== \"undefined\" && typeof window.document !== \"undefined\" && typeof window.document.createElement !== \"undefined\");\nconst isServerEnvironment = !canUseDOM;\nconst shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore$2;\nconst useSyncExternalStore = \"useSyncExternalStore\" in React ? (module => module.useSyncExternalStore)(React) : shim;\n\nconst DataRouterContext = /*#__PURE__*/React.createContext(null);\n\nif (process.env.NODE_ENV !== \"production\") {\n DataRouterContext.displayName = \"DataRouter\";\n}\n\nconst DataRouterStateContext = /*#__PURE__*/React.createContext(null);\n\nif (process.env.NODE_ENV !== \"production\") {\n DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nconst AwaitContext = /*#__PURE__*/React.createContext(null);\n\nif (process.env.NODE_ENV !== \"production\") {\n AwaitContext.displayName = \"Await\";\n}\n\nconst NavigationContext = /*#__PURE__*/React.createContext(null);\n\nif (process.env.NODE_ENV !== \"production\") {\n NavigationContext.displayName = \"Navigation\";\n}\n\nconst LocationContext = /*#__PURE__*/React.createContext(null);\n\nif (process.env.NODE_ENV !== \"production\") {\n LocationContext.displayName = \"Location\";\n}\n\nconst RouteContext = /*#__PURE__*/React.createContext({\n outlet: null,\n matches: []\n});\n\nif (process.env.NODE_ENV !== \"production\") {\n RouteContext.displayName = \"Route\";\n}\n\nconst RouteErrorContext = /*#__PURE__*/React.createContext(null);\n\nif (process.env.NODE_ENV !== \"production\") {\n RouteErrorContext.displayName = \"RouteError\";\n}\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\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n return _extends.apply(this, arguments);\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 */\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 <Router> 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; // 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\n if (basename !== \"/\") {\n joinedPathname = pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n }\n\n return navigator.createHref({\n pathname: joinedPathname,\n search,\n hash\n });\n}\n/**\n * Returns true if this component is a descendant of a <Router>.\n *\n * @see https://reactrouter.com/hooks/use-in-router-context\n */\n\nfunction useInRouterContext() {\n return React.useContext(LocationContext) != null;\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 */\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 <Router> component.\") : UNSAFE_invariant(false) : void 0;\n return React.useContext(LocationContext).location;\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 */\n\nfunction useNavigationType() {\n return React.useContext(LocationContext).navigationType;\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 * <NavLink>.\n *\n * @see https://reactrouter.com/hooks/use-match\n */\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 <Router> component.\") : UNSAFE_invariant(false) : void 0;\n let {\n pathname\n } = useLocation();\n return React.useMemo(() => matchPath(pattern, pathname), [pathname, pattern]);\n}\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\n\n/**\n * Returns an imperative method for changing the location. Used by <Link>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 !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 <Router> component.\") : UNSAFE_invariant(false) : void 0;\n let {\n basename,\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_getPathContributingMatches(matches).map(match => match.pathnameBase));\n let activeRef = React.useRef(false);\n React.useEffect(() => {\n activeRef.current = true;\n });\n let navigate = React.useCallback(function (to, options) {\n if (options === void 0) {\n options = {};\n }\n\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(activeRef.current, \"You should call navigate() in a React.useEffect(), not when \" + \"your component is first rendered.\") : void 0;\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n navigator.go(to);\n return;\n }\n\n let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === \"path\"); // If we're operating within a basename, prepend it to the pathname prior\n // to handing off to history. If this is a root navigation, then we\n // navigate to the raw basename which allows the basename to have full\n // control over the presence of a trailing slash on root links\n\n if (basename !== \"/\") {\n path.pathname = path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);\n }, [basename, navigator, routePathnamesJson, locationPathname]);\n return navigate;\n}\nconst OutletContext = /*#__PURE__*/React.createContext(null);\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 */\n\nfunction useOutletContext() {\n return React.useContext(OutletContext);\n}\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by <Outlet> to render child routes.\n *\n * @see https://reactrouter.com/hooks/use-outlet\n */\n\nfunction useOutlet(context) {\n let outlet = React.useContext(RouteContext).outlet;\n\n if (outlet) {\n return /*#__PURE__*/React.createElement(OutletContext.Provider, {\n value: context\n }, outlet);\n }\n\n return outlet;\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 */\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 * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/hooks/use-resolved-path\n */\n\nfunction useResolvedPath(to, _temp2) {\n let {\n relative\n } = _temp2 === void 0 ? {} : _temp2;\n let {\n matches\n } = React.useContext(RouteContext);\n let {\n pathname: locationPathname\n } = useLocation();\n let routePathnamesJson = JSON.stringify(UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));\n return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === \"path\"), [to, routePathnamesJson, locationPathname, relative]);\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 <Outlet> to render their child route's\n * element.\n *\n * @see https://reactrouter.com/hooks/use-routes\n */\n\nfunction useRoutes(routes, locationArg) {\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 <Router> component.\") : UNSAFE_invariant(false) : void 0;\n let {\n navigator\n } = React.useContext(NavigationContext);\n let dataRouterStateContext = React.useContext(DataRouterStateContext);\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\n if (process.env.NODE_ENV !== \"production\") {\n // You won't get a warning about 2 different <Routes> under a <Route>\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 // <Routes>\n // {/* This route path MUST end with /* because otherwise\n // it will never match /blog/post/123 */}\n // <Route path=\"blog\" element={<Blog />} />\n // <Route path=\"blog/feed\" element={<BlogFeed />} />\n // </Routes>\n //\n // function Blog() {\n // return (\n // <Routes>\n // <Route path=\"post/:id\" element={<Post />} />\n // </Routes>\n // );\n // }\n let parentPath = parentRoute && parentRoute.path || \"\";\n warningOnce(parentPathname, !parentRoute || parentPath.endsWith(\"*\"), \"You rendered descendant <Routes> (or called `useRoutes()`) at \" + (\"\\\"\" + parentPathname + \"\\\" (under <Route path=\\\"\" + parentPath + \"\\\">) but the \") + \"parent route path has no trailing \\\"*\\\". This means if you navigate \" + \"deeper, the parent won't match anymore and therefore the child \" + \"routes will never render.\\n\\n\" + (\"Please change the parent <Route path=\\\"\" + parentPath + \"\\\"> to <Route \") + (\"path=\\\"\" + (parentPath === \"/\" ? \"*\" : parentPath + \"/*\") + \"\\\">.\"));\n }\n\n let locationFromContext = useLocation();\n let location;\n\n if (locationArg) {\n var _parsedLocationArg$pa;\n\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 `<Routes location>` or `useRoutes(routes, location)`, \" + \"the location pathname must begin with the portion of the URL pathname that was \" + (\"matched by all parent routes. The current pathname base is \\\"\" + parentPathnameBase + \"\\\" \") + (\"but pathname \\\"\" + parsedLocationArg.pathname + \"\\\" was given in the `location` prop.\")) : UNSAFE_invariant(false) : void 0;\n location = parsedLocationArg;\n } else {\n location = locationFromContext;\n }\n\n let pathname = location.pathname || \"/\";\n let remainingPathname = parentPathnameBase === \"/\" ? pathname : pathname.slice(parentPathnameBase.length) || \"/\";\n let matches = matchRoutes(routes, {\n pathname: remainingPathname\n });\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, \"Matched leaf route at location \\\"\" + location.pathname + location.search + location.hash + \"\\\" \" + \"does not have an element or Component. This means it will render an <Outlet /> with a \" + \"null value by default resulting in an \\\"empty\\\" page.\") : void 0;\n }\n\n let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {\n params: Object.assign({}, parentParams, match.params),\n pathname: joinPaths([parentPathnameBase, // 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, // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])\n })), parentMatches, dataRouterStateContext || undefined); // 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\n\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\n return renderedMatches;\n}\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\n if (process.env.NODE_ENV !== \"production\") {\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\\xA0\", /*#__PURE__*/React.createElement(\"code\", {\n style: codeStyles\n }, \"ErrorBoundary\"), \" prop on\\xA0\", /*#__PURE__*/React.createElement(\"code\", {\n style: codeStyles\n }, \"<Route>\")));\n }\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}\n\nclass RenderErrorBoundary extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n location: props.location,\n error: props.error\n };\n }\n\n static getDerivedStateFromError(error) {\n return {\n error: error\n };\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) {\n return {\n error: props.error,\n location: props.location\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\n\n return {\n error: props.error || state.error,\n location: state.location\n };\n }\n\n componentDidCatch(error, errorInfo) {\n console.error(\"React Router caught the following error during render\", error, errorInfo);\n }\n\n render() {\n return this.state.error ? /*#__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\n}\n\nfunction RenderedRoute(_ref) {\n let {\n routeContext,\n match,\n children\n } = _ref;\n let dataRouterContext = React.useContext(DataRouterContext); // Track how deep we got in our render pass to emulate SSR componentDidCatch\n // in a DataStaticRouter\n\n if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {\n dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n }\n\n return /*#__PURE__*/React.createElement(RouteContext.Provider, {\n value: routeContext\n }, children);\n}\n\nfunction _renderMatches(matches, parentMatches, dataRouterState) {\n if (parentMatches === void 0) {\n parentMatches = [];\n }\n\n if (matches == null) {\n if (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\n let renderedMatches = matches; // If we have data errors, trim matches to the highest error boundary\n\n let errors = dataRouterState == null ? void 0 : dataRouterState.errors;\n\n if (errors != null) {\n let errorIndex = renderedMatches.findIndex(m => m.route.id && (errors == null ? void 0 : errors[m.route.id]));\n !(errorIndex >= 0) ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"Could not find a matching route for the current errors: \" + errors) : UNSAFE_invariant(false) : void 0;\n renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));\n }\n\n return renderedMatches.reduceRight((outlet, match, index) => {\n let error = match.route.id ? errors == null ? void 0 : errors[match.route.id] : null; // Only data routers handle errors\n\n let errorElement = null;\n\n if (dataRouterState) {\n if (match.route.ErrorBoundary) {\n errorElement = /*#__PURE__*/React.createElement(match.route.ErrorBoundary, null);\n } else if (match.route.errorElement) {\n errorElement = match.route.errorElement;\n } else {\n errorElement = /*#__PURE__*/React.createElement(DefaultErrorComponent, null);\n }\n }\n\n let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n\n let getChildren = () => {\n let children = outlet;\n\n if (error) {\n children = errorElement;\n } else if (match.route.Component) {\n children = /*#__PURE__*/React.createElement(match.route.Component, null);\n } else if (match.route.element) {\n children = match.route.element;\n }\n\n return /*#__PURE__*/React.createElement(RenderedRoute, {\n match: match,\n routeContext: {\n outlet,\n matches\n },\n children: children\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\n\n return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /*#__PURE__*/React.createElement(RenderErrorBoundary, {\n location: dataRouterState.location,\n component: errorElement,\n error: error,\n children: getChildren(),\n routeContext: {\n outlet: null,\n matches\n }\n }) : getChildren();\n }, null);\n}\nvar DataRouterHook;\n\n(function (DataRouterHook) {\n DataRouterHook[\"UseBlocker\"] = \"useBlocker\";\n DataRouterHook[\"UseRevalidator\"] = \"useRevalidator\";\n})(DataRouterHook || (DataRouterHook = {}));\n\nvar DataRouterStateHook;\n\n(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 || (DataRouterStateHook = {}));\n\nfunction getDataRouterConsoleError(hookName) {\n return hookName + \" must be used within a data router. See https://reactrouter.com/routers/picking-a-router.\";\n}\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}\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}\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\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 * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\n\n\nfunction useNavigation() {\n let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n return state.navigation;\n}\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\n\nfunction useRevalidator() {\n let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n return {\n revalidate: dataRouterContext.router.revalidate,\n state: 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 */\n\nfunction useMatches() {\n let {\n matches,\n loaderData\n } = useDataRouterState(DataRouterStateHook.UseMatches);\n return React.useMemo(() => matches.map(match => {\n let {\n pathname,\n params\n } = match; // Note: This structure matches that created by createUseMatchesMatch\n // in the @remix-run/router , so if you change this please also change\n // that :) Eventually we'll DRY this up\n\n return {\n id: match.route.id,\n pathname,\n params,\n data: loaderData[match.route.id],\n handle: match.route.handle\n };\n }), [matches, loaderData]);\n}\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\n\nfunction useLoaderData() {\n let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n if (state.errors && state.errors[routeId] != null) {\n console.error(\"You cannot `useLoaderData` in an errorElement (routeId: \" + routeId + \")\");\n return undefined;\n }\n\n return state.loaderData[routeId];\n}\n/**\n * Returns the loaderData for the given routeId\n */\n\nfunction useRouteLoaderData(routeId) {\n let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n return state.loaderData[routeId];\n}\n/**\n * Returns the action data for the nearest ancestor Route action\n */\n\nfunction useActionData() {\n let state = useDataRouterState(DataRouterStateHook.UseActionData);\n let route = React.useContext(RouteContext);\n !route ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"useActionData must be used inside a RouteContext\") : UNSAFE_invariant(false) : void 0;\n return Object.values((state == null ? void 0 : state.actionData) || {})[0];\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 */\n\nfunction useRouteError() {\n var _state$errors;\n\n let error = React.useContext(RouteErrorContext);\n let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError); // If this was a render error, we put it in a RouteError context inside\n // of RenderErrorBoundary\n\n if (error) {\n return error;\n } // Otherwise look for errors from our data router state\n\n\n return (_state$errors = state.errors) == null ? void 0 : _state$errors[routeId];\n}\n/**\n * Returns the happy-path data from the nearest ancestor <Await /> value\n */\n\nfunction useAsyncValue() {\n let value = React.useContext(AwaitContext);\n return value == null ? void 0 : value._data;\n}\n/**\n * Returns the error from the nearest ancestor <Await /> value\n */\n\nfunction useAsyncError() {\n let value = React.useContext(AwaitContext);\n return value == null ? void 0 : value._error;\n}\nlet blockerId = 0;\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 */\n\nfunction useBlocker(shouldBlock) {\n let {\n router\n } = useDataRouterContext(DataRouterHook.UseBlocker);\n let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n let [blockerKey] = React.useState(() => String(++blockerId));\n let blockerFunction = React.useCallback(args => {\n return typeof shouldBlock === \"function\" ? !!shouldBlock(args) : !!shouldBlock;\n }, [shouldBlock]);\n let blocker = router.getBlocker(blockerKey, blockerFunction); // Cleanup on unmount\n\n React.useEffect(() => () => router.deleteBlocker(blockerKey), [router, blockerKey]); // Prefer the blocker from state since DataRouterContext is memoized so this\n // ensures we update on blocker state updates\n\n return state.blockers.get(blockerKey) || blocker;\n}\nconst alreadyWarned = {};\n\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 * Given a Remix Router instance, render the appropriate UI\n */\nfunction RouterProvider(_ref) {\n let {\n fallbackElement,\n router\n } = _ref;\n let getState = React.useCallback(() => router.state, [router]); // Sync router state to our component state to force re-renders\n\n let state = useSyncExternalStore(router.subscribe, getState, // We have to provide this so React@18 doesn't complain during hydration,\n // but we pass our serialized hydration data into the router so state here\n // is already synced with what the server saw\n getState);\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]); // 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 <script> here\n // containing the hydrated server-side staticContext (from StaticRouterProvider).\n // useId relies on the component tree structure to generate deterministic id's\n // so we need to ensure it remains the same on the client even though\n // we don't need the <script> tag\n\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(DataRouterContext.Provider, {\n value: dataRouterContext\n }, /*#__PURE__*/React.createElement(DataRouterStateContext.Provider, {\n value: state\n }, /*#__PURE__*/React.createElement(Router, {\n basename: router.basename,\n location: router.state.location,\n navigationType: router.state.historyAction,\n navigator: navigator\n }, router.state.initialized ? /*#__PURE__*/React.createElement(Routes, null) : fallbackElement))), null);\n}\n\n/**\n * A <Router> that stores all entries in memory.\n *\n * @see https://reactrouter.com/router-components/memory-router\n */\nfunction MemoryRouter(_ref2) {\n let {\n basename,\n children,\n initialEntries,\n initialIndex\n } = _ref2;\n let historyRef = React.useRef();\n\n if (historyRef.current == null) {\n historyRef.current = createMemoryHistory({\n initialEntries,\n initialIndex,\n v5Compat: true\n });\n }\n\n let history = historyRef.current;\n let [state, setState] = React.useState({\n action: history.action,\n location: history.location\n });\n React.useLayoutEffect(() => history.listen(setState), [history]);\n return /*#__PURE__*/React.createElement(Router, {\n basename: basename,\n children: children,\n location: state.location,\n navigationType: state.action,\n navigator: history\n });\n}\n\n/**\n * Changes the current location.\n *\n * Note: This API is mostly useful in React.Component subclasses that are not\n * able to use hooks. In functional components, we recommend you use the\n * `useNavigate` hook instead.\n *\n * @see https://reactrouter.com/components/navigate\n */\nfunction Navigate(_ref3) {\n let {\n to,\n replace,\n state,\n relative\n } = _ref3;\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of\n // the router loaded. We can help them understand how to avoid that.\n \"<Navigate> may be used only in the context of a <Router> component.\") : UNSAFE_invariant(false) : void 0;\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(!React.useContext(NavigationContext).static, \"<Navigate> must not be used on the initial render in a <StaticRouter>. \" + \"This is a no-op, but you should modify your code so the <Navigate> is \" + \"only ever rendered in response to some user interaction or state change.\") : void 0;\n let dataRouterState = React.useContext(DataRouterStateContext);\n let navigate = useNavigate();\n React.useEffect(() => {\n // Avoid kicking off multiple navigations if we're in the middle of a\n // data-router navigation, since components get re-rendered when we enter\n // a submitting/loading state\n if (dataRouterState && dataRouterState.navigation.state !== \"idle\") {\n return;\n }\n\n navigate(to, {\n replace,\n state,\n relative\n });\n });\n return null;\n}\n\n/**\n * Renders the child route's element, if there is one.\n *\n * @see https://reactrouter.com/components/outlet\n */\nfunction Outlet(props) {\n return useOutlet(props.context);\n}\n\n/**\n * Declares an element that should be rendered at a certain URL path.\n *\n * @see https://reactrouter.com/components/route\n */\nfunction Route(_props) {\n process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"A <Route> is only ever to be used as the child of <Routes> element, \" + \"never rendered directly. Please wrap your <Route> in a <Routes>.\") : UNSAFE_invariant(false) ;\n}\n\n/**\n * Provides location context for the rest of the app.\n *\n * Note: You usually won't render a <Router> directly. Instead, you'll render a\n * router that is more specific to your environment such as a <BrowserRouter>\n * in web browsers or a <StaticRouter> for server rendering.\n *\n * @see https://reactrouter.com/router-components/router\n */\nfunction Router(_ref4) {\n let {\n basename: basenameProp = \"/\",\n children = null,\n location: locationProp,\n navigationType = Action.Pop,\n navigator,\n static: staticProp = false\n } = _ref4;\n !!useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"You cannot render a <Router> inside another <Router>.\" + \" You should never have more than one in your app.\") : UNSAFE_invariant(false) : void 0; // Preserve trailing slashes on basename, so we can let the user control\n // the enforcement of trailing slashes throughout the app\n\n let basename = basenameProp.replace(/^\\/*/, \"/\");\n let navigationContext = React.useMemo(() => ({\n basename,\n navigator,\n static: staticProp\n }), [basename, navigator, staticProp]);\n\n if (typeof locationProp === \"string\") {\n locationProp = parsePath(locationProp);\n }\n\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n state = null,\n key = \"default\"\n } = locationProp;\n let locationContext = React.useMemo(() => {\n let trailingPathname = stripBasename(pathname, basename);\n\n if (trailingPathname == null) {\n return null;\n }\n\n return {\n location: {\n pathname: trailingPathname,\n search,\n hash,\n state,\n key\n },\n navigationType\n };\n }, [basename, pathname, search, hash, state, key, navigationType]);\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(locationContext != null, \"<Router basename=\\\"\" + basename + \"\\\"> is not able to match the URL \" + (\"\\\"\" + pathname + search + hash + \"\\\" because it does not start with the \") + \"basename, so the <Router> won't render anything.\") : void 0;\n\n if (locationContext == null) {\n return null;\n }\n\n return /*#__PURE__*/React.createElement(NavigationContext.Provider, {\n value: navigationContext\n }, /*#__PURE__*/React.createElement(LocationContext.Provider, {\n children: children,\n value: locationContext\n }));\n}\n\n/**\n * A container for a nested tree of <Route> elements that renders the branch\n * that best matches the current location.\n *\n * @see https://reactrouter.com/components/routes\n */\nfunction Routes(_ref5) {\n let {\n children,\n location\n } = _ref5;\n let dataRouterContext = React.useContext(DataRouterContext); // When in a DataRouterContext _without_ children, we use the router routes\n // directly. If we have children, then we're in a descendant tree and we\n // need to use child routes.\n\n let routes = dataRouterContext && !children ? dataRouterContext.router.routes : createRoutesFromChildren(children);\n return useRoutes(routes, location);\n}\n\n/**\n * Component to use for rendering lazily loaded data from returning defer()\n * in a loader function\n */\nfunction Await(_ref6) {\n let {\n children,\n errorElement,\n resolve\n } = _ref6;\n return /*#__PURE__*/React.createElement(AwaitErrorBoundary, {\n resolve: resolve,\n errorElement: errorElement\n }, /*#__PURE__*/React.createElement(ResolveAwait, null, children));\n}\nvar AwaitRenderStatus;\n\n(function (AwaitRenderStatus) {\n AwaitRenderStatus[AwaitRenderStatus[\"pending\"] = 0] = \"pending\";\n AwaitRenderStatus[AwaitRenderStatus[\"success\"] = 1] = \"success\";\n AwaitRenderStatus[AwaitRenderStatus[\"error\"] = 2] = \"error\";\n})(AwaitRenderStatus || (AwaitRenderStatus = {}));\n\nconst neverSettledPromise = new Promise(() => {});\n\nclass AwaitErrorBoundary extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n error: null\n };\n }\n\n static getDerivedStateFromError(error) {\n return {\n error\n };\n }\n\n componentDidCatch(error, errorInfo) {\n console.error(\"<Await> caught the following error during render\", error, errorInfo);\n }\n\n render() {\n let {\n children,\n errorElement,\n resolve\n } = this.props;\n let promise = null;\n let status = AwaitRenderStatus.pending;\n\n if (!(resolve instanceof Promise)) {\n // Didn't get a promise - provide as a resolved promise\n status = AwaitRenderStatus.success;\n promise = Promise.resolve();\n Object.defineProperty(promise, \"_tracked\", {\n get: () => true\n });\n Object.defineProperty(promise, \"_data\", {\n get: () => resolve\n });\n } else if (this.state.error) {\n // Caught a render error, provide it as a rejected promise\n status = AwaitRenderStatus.error;\n let renderError = this.state.error;\n promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings\n\n Object.defineProperty(promise, \"_tracked\", {\n get: () => true\n });\n Object.defineProperty(promise, \"_error\", {\n get: () => renderError\n });\n } else if (resolve._tracked) {\n // Already tracked promise - check contents\n promise = resolve;\n status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;\n } else {\n // Raw (untracked) promise - track it\n status = AwaitRenderStatus.pending;\n Object.defineProperty(resolve, \"_tracked\", {\n get: () => true\n });\n promise = resolve.then(data => Object.defineProperty(resolve, \"_data\", {\n get: () => data\n }), error => Object.defineProperty(resolve, \"_error\", {\n get: () => error\n }));\n }\n\n if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {\n // Freeze the UI by throwing a never resolved promise\n throw neverSettledPromise;\n }\n\n if (status === AwaitRenderStatus.error && !errorElement) {\n // No errorElement, throw to the nearest route-level error boundary\n throw promise._error;\n }\n\n if (status === AwaitRenderStatus.error) {\n // Render via our errorElement\n return /*#__PURE__*/React.createElement(AwaitContext.Provider, {\n value: promise,\n children: errorElement\n });\n }\n\n if (status === AwaitRenderStatus.success) {\n // Render children with resolved value\n return /*#__PURE__*/React.createElement(AwaitContext.Provider, {\n value: promise,\n children: children\n });\n } // Throw to the suspense boundary\n\n\n throw promise;\n }\n\n}\n/**\n * @private\n * Indirection to leverage useAsyncValue for a render-prop API on <Await>\n */\n\n\nfunction ResolveAwait(_ref7) {\n let {\n children\n } = _ref7;\n let data = useAsyncValue();\n let toRender = typeof children === \"function\" ? children(data) : children;\n return /*#__PURE__*/React.createElement(React.Fragment, null, toRender);\n} ///////////////////////////////////////////////////////////////////////////////\n// UTILS\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Creates a route config from a React \"children\" object, which is usually\n * either a `<Route>` element or an array of them. Used internally by\n * `<Routes>` to create a route config from its children.\n *\n * @see https://reactrouter.com/utils/create-routes-from-children\n */\n\n\nfunction createRoutesFromChildren(children, parentPath) {\n if (parentPath === void 0) {\n parentPath = [];\n }\n\n let routes = [];\n React.Children.forEach(children, (element, index) => {\n if (! /*#__PURE__*/React.isValidElement(element)) {\n // Ignore non-elements. This allows people to more easily inline\n // conditionals in their route config.\n return;\n }\n\n let treePath = [...parentPath, index];\n\n if (element.type === React.Fragment) {\n // Transparently support React.Fragment and its children.\n routes.push.apply(routes, createRoutesFromChildren(element.props.children, treePath));\n return;\n }\n\n !(element.type === Route) ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"[\" + (typeof element.type === \"string\" ? element.type : element.type.name) + \"] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>\") : UNSAFE_invariant(false) : void 0;\n !(!element.props.index || !element.props.children) ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"An index route cannot have child routes.\") : UNSAFE_invariant(false) : void 0;\n let route = {\n id: element.props.id || treePath.join(\"-\"),\n caseSensitive: element.props.caseSensitive,\n element: element.props.element,\n Component: element.props.Component,\n index: element.props.index,\n path: element.props.path,\n loader: element.props.loader,\n action: element.props.action,\n errorElement: element.props.errorElement,\n ErrorBoundary: element.props.ErrorBoundary,\n hasErrorBoundary: element.props.ErrorBoundary != null || element.props.errorElement != null,\n shouldRevalidate: element.props.shouldRevalidate,\n handle: element.props.handle,\n lazy: element.props.lazy\n };\n\n if (element.props.children) {\n route.children = createRoutesFromChildren(element.props.children, treePath);\n }\n\n routes.push(route);\n });\n return routes;\n}\n/**\n * Renders the result of `matchRoutes()` into a React element.\n */\n\nfunction renderMatches(matches) {\n return _renderMatches(matches);\n}\n\nfunction detectErrorBoundary(route) {\n if (process.env.NODE_ENV !== \"production\") {\n if (route.Component && route.element) {\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(false, \"You should not include both `Component` and `element` on your route - \" + \"`element` will be ignored.\") : void 0;\n }\n\n if (route.ErrorBoundary && route.errorElement) {\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(false, \"You should not include both `ErrorBoundary` and `errorElement` on your route - \" + \"`errorElement` will be ignored.\") : void 0;\n }\n } // Note: this check also occurs in createRoutesFromChildren so update\n // there if you change this\n\n\n return Boolean(route.ErrorBoundary) || Boolean(route.errorElement);\n}\n\nfunction createMemoryRouter(routes, opts) {\n return createRouter({\n basename: opts == null ? void 0 : opts.basename,\n future: opts == null ? void 0 : opts.future,\n history: createMemoryHistory({\n initialEntries: opts == null ? void 0 : opts.initialEntries,\n initialIndex: opts == null ? void 0 : opts.initialIndex\n }),\n hydrationData: opts == null ? void 0 : opts.hydrationData,\n routes,\n detectErrorBoundary\n }).initialize();\n} ///////////////////////////////////////////////////////////////////////////////\n\nexport { Await, MemoryRouter, Navigate, Outlet, Route, Router, RouterProvider, Routes, DataRouterContext as UNSAFE_DataRouterContext, DataRouterStateContext as UNSAFE_DataRouterStateContext, LocationContext as UNSAFE_LocationContext, NavigationContext as UNSAFE_NavigationContext, RouteContext as UNSAFE_RouteContext, detectErrorBoundary as UNSAFE_detectErrorBoundary, createMemoryRouter, createRoutesFromChildren, createRoutesFromChildren as createRoutesFromElements, renderMatches, useBlocker as unstable_useBlocker, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes };\n//# sourceMappingURL=index.js.map\n","/**\n * React Router DOM v6.10.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_detectErrorBoundary, Router, UNSAFE_NavigationContext, useHref, useResolvedPath, useLocation, UNSAFE_DataRouterStateContext, useNavigate, createPath, UNSAFE_RouteContext, useMatches, useNavigation, unstable_useBlocker, UNSAFE_DataRouterContext } from 'react-router';\nexport { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, renderMatches, resolvePath, unstable_useBlocker, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes } from 'react-router';\nimport { createRouter, createBrowserHistory, createHashHistory, ErrorResponse, stripBasename, UNSAFE_warning, UNSAFE_invariant, joinPaths } 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\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n return _extends.apply(this, arguments);\n}\n\nfunction _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n}\n\nconst defaultMethod = \"get\";\nconst defaultEncType = \"application/x-www-form-urlencoded\";\nfunction isHtmlElement(object) {\n return object != null && typeof object.tagName === \"string\";\n}\nfunction isButtonElement(object) {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"button\";\n}\nfunction isFormElement(object) {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"form\";\n}\nfunction isInputElement(object) {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"input\";\n}\n\nfunction isModifiedEvent(event) {\n return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nfunction shouldProcessLinkClick(event, target) {\n return event.button === 0 && ( // Ignore everything but left clicks\n !target || target === \"_self\") && // Let browser handle \"target=_blank\" etc.\n !isModifiedEvent(event) // Ignore clicks with modifier keys\n ;\n}\n/**\n * Creates a URLSearchParams object using the given initializer.\n *\n * This is identical to `new URLSearchParams(init)` except it also\n * supports arrays as values in the object form of the initializer\n * instead of just strings. This is convenient when you need multiple\n * values for a given key, but don't want to use an array initializer.\n *\n * For example, instead of:\n *\n * let searchParams = new URLSearchParams([\n * ['sort', 'name'],\n * ['sort', 'price']\n * ]);\n *\n * you can do:\n *\n * let searchParams = createSearchParams({\n * sort: ['name', 'price']\n * });\n */\n\nfunction createSearchParams(init) {\n if (init === void 0) {\n init = \"\";\n }\n\n return new URLSearchParams(typeof init === \"string\" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {\n let value = init[key];\n return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]);\n }, []));\n}\nfunction getSearchParamsForLocation(locationSearch, defaultSearchParams) {\n let searchParams = createSearchParams(locationSearch);\n\n if (defaultSearchParams) {\n for (let key of defaultSearchParams.keys()) {\n if (!searchParams.has(key)) {\n defaultSearchParams.getAll(key).forEach(value => {\n searchParams.append(key, value);\n });\n }\n }\n }\n\n return searchParams;\n}\nfunction getFormSubmissionInfo(target, defaultAction, options) {\n let method;\n let action;\n let encType;\n let formData;\n\n if (isFormElement(target)) {\n let submissionTrigger = options.submissionTrigger;\n method = options.method || target.getAttribute(\"method\") || defaultMethod;\n action = options.action || target.getAttribute(\"action\") || defaultAction;\n encType = options.encType || target.getAttribute(\"enctype\") || defaultEncType;\n formData = new FormData(target);\n\n if (submissionTrigger && submissionTrigger.name) {\n formData.append(submissionTrigger.name, submissionTrigger.value);\n }\n } else if (isButtonElement(target) || isInputElement(target) && (target.type === \"submit\" || target.type === \"image\")) {\n let form = target.form;\n\n if (form == null) {\n throw new Error(\"Cannot submit a <button> or <input type=\\\"submit\\\"> without a <form>\");\n } // <button>/<input type=\"submit\"> may override attributes of <form>\n\n\n method = options.method || target.getAttribute(\"formmethod\") || form.getAttribute(\"method\") || defaultMethod;\n action = options.action || target.getAttribute(\"formaction\") || form.getAttribute(\"action\") || defaultAction;\n encType = options.encType || target.getAttribute(\"formenctype\") || form.getAttribute(\"enctype\") || defaultEncType;\n formData = new FormData(form); // Include name + value from a <button>, appending in case the button name\n // matches an existing input name\n\n if (target.name) {\n formData.append(target.name, target.value);\n }\n } else if (isHtmlElement(target)) {\n throw new Error(\"Cannot submit element that is not <form>, <button>, or \" + \"<input type=\\\"submit|image\\\">\");\n } else {\n method = options.method || defaultMethod;\n action = options.action || defaultAction;\n encType = options.encType || defaultEncType;\n\n if (target instanceof FormData) {\n formData = target;\n } else {\n formData = new FormData();\n\n if (target instanceof URLSearchParams) {\n for (let [name, value] of target) {\n formData.append(name, value);\n }\n } else if (target != null) {\n for (let name of Object.keys(target)) {\n formData.append(name, target[name]);\n }\n }\n }\n }\n\n let {\n protocol,\n host\n } = window.location;\n let url = new URL(action, protocol + \"//\" + host);\n return {\n url,\n method: method.toLowerCase(),\n encType,\n formData\n };\n}\n\nconst _excluded = [\"onClick\", \"relative\", \"reloadDocument\", \"replace\", \"state\", \"target\", \"to\", \"preventScrollReset\"],\n _excluded2 = [\"aria-current\", \"caseSensitive\", \"className\", \"end\", \"style\", \"to\", \"children\"],\n _excluded3 = [\"reloadDocument\", \"replace\", \"method\", \"action\", \"onSubmit\", \"fetcherKey\", \"routeId\", \"relative\", \"preventScrollReset\"];\nfunction createBrowserRouter(routes, opts) {\n return createRouter({\n basename: opts == null ? void 0 : opts.basename,\n future: opts == null ? void 0 : opts.future,\n history: createBrowserHistory({\n window: opts == null ? void 0 : opts.window\n }),\n hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),\n routes,\n detectErrorBoundary: UNSAFE_detectErrorBoundary\n }).initialize();\n}\nfunction createHashRouter(routes, opts) {\n return createRouter({\n basename: opts == null ? void 0 : opts.basename,\n future: opts == null ? void 0 : opts.future,\n history: createHashHistory({\n window: opts == null ? void 0 : opts.window\n }),\n hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),\n routes,\n detectErrorBoundary: UNSAFE_detectErrorBoundary\n }).initialize();\n}\n\nfunction parseHydrationData() {\n var _window;\n\n let state = (_window = window) == null ? void 0 : _window.__staticRouterHydrationData;\n\n if (state && state.errors) {\n state = _extends({}, state, {\n errors: deserializeErrors(state.errors)\n });\n }\n\n return state;\n}\n\nfunction deserializeErrors(errors) {\n if (!errors) return null;\n let entries = Object.entries(errors);\n let serialized = {};\n\n for (let [key, val] of entries) {\n // Hey you! If you change this, please change the corresponding logic in\n // serializeErrors in react-router-dom/server.tsx :)\n if (val && val.__type === \"RouteErrorResponse\") {\n serialized[key] = new ErrorResponse(val.status, val.statusText, val.data, val.internal === true);\n } else if (val && val.__type === \"Error\") {\n let error = new Error(val.message); // Wipe away the client-side stack trace. Nothing to fill it in with\n // because we don't serialize SSR stack traces for security reasons\n\n error.stack = \"\";\n serialized[key] = error;\n } else {\n serialized[key] = val;\n }\n }\n\n return serialized;\n}\n/**\n * A `<Router>` for use in web browsers. Provides the cleanest URLs.\n */\n\n\nfunction BrowserRouter(_ref) {\n let {\n basename,\n children,\n window\n } = _ref;\n let historyRef = React.useRef();\n\n if (historyRef.current == null) {\n historyRef.current = createBrowserHistory({\n window,\n v5Compat: true\n });\n }\n\n let history = historyRef.current;\n let [state, setState] = React.useState({\n action: history.action,\n location: history.location\n });\n React.useLayoutEffect(() => history.listen(setState), [history]);\n return /*#__PURE__*/React.createElement(Router, {\n basename: basename,\n children: children,\n location: state.location,\n navigationType: state.action,\n navigator: history\n });\n}\n/**\n * A `<Router>` for use in web browsers. Stores the location in the hash\n * portion of the URL so it is not sent to the server.\n */\n\nfunction HashRouter(_ref2) {\n let {\n basename,\n children,\n window\n } = _ref2;\n let historyRef = React.useRef();\n\n if (historyRef.current == null) {\n historyRef.current = createHashHistory({\n window,\n v5Compat: true\n });\n }\n\n let history = historyRef.current;\n let [state, setState] = React.useState({\n action: history.action,\n location: history.location\n });\n React.useLayoutEffect(() => history.listen(setState), [history]);\n return /*#__PURE__*/React.createElement(Router, {\n basename: basename,\n children: children,\n location: state.location,\n navigationType: state.action,\n navigator: history\n });\n}\n/**\n * A `<Router>` that accepts a pre-instantiated history object. It's important\n * to note that using your own history object is highly discouraged and may add\n * two versions of the history library to your bundles unless you use the same\n * version of the history library that React Router uses internally.\n */\n\nfunction HistoryRouter(_ref3) {\n let {\n basename,\n children,\n history\n } = _ref3;\n const [state, setState] = React.useState({\n action: history.action,\n location: history.location\n });\n React.useLayoutEffect(() => history.listen(setState), [history]);\n return /*#__PURE__*/React.createElement(Router, {\n basename: basename,\n children: children,\n location: state.location,\n navigationType: state.action,\n navigator: history\n });\n}\n\nif (process.env.NODE_ENV !== \"production\") {\n HistoryRouter.displayName = \"unstable_HistoryRouter\";\n}\nconst isBrowser = typeof window !== \"undefined\" && typeof window.document !== \"undefined\" && typeof window.document.createElement !== \"undefined\";\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n/**\n * The public API for rendering a history-aware <a>.\n */\n\nconst Link = /*#__PURE__*/React.forwardRef(function LinkWithRef(_ref4, ref) {\n let {\n onClick,\n relative,\n reloadDocument,\n replace,\n state,\n target,\n to,\n preventScrollReset\n } = _ref4,\n rest = _objectWithoutPropertiesLoose(_ref4, _excluded);\n\n let {\n basename\n } = React.useContext(UNSAFE_NavigationContext); // Rendered into <a href> for absolute URLs\n\n let absoluteHref;\n let isExternal = false;\n\n if (typeof to === \"string\" && ABSOLUTE_URL_REGEX.test(to)) {\n // Render the absolute href server- and client-side\n absoluteHref = to; // Only check for external origins client-side\n\n if (isBrowser) {\n let currentUrl = new URL(window.location.href);\n let targetUrl = to.startsWith(\"//\") ? new URL(currentUrl.protocol + to) : new URL(to);\n let path = stripBasename(targetUrl.pathname, basename);\n\n if (targetUrl.origin === currentUrl.origin && path != null) {\n // Strip the protocol/origin/basename for same-origin absolute URLs\n to = path + targetUrl.search + targetUrl.hash;\n } else {\n isExternal = true;\n }\n }\n } // Rendered into <a href> for relative URLs\n\n\n let href = useHref(to, {\n relative\n });\n let internalOnClick = useLinkClickHandler(to, {\n replace,\n state,\n target,\n preventScrollReset,\n relative\n });\n\n function handleClick(event) {\n if (onClick) onClick(event);\n\n if (!event.defaultPrevented) {\n internalOnClick(event);\n }\n }\n\n return (\n /*#__PURE__*/\n // eslint-disable-next-line jsx-a11y/anchor-has-content\n React.createElement(\"a\", _extends({}, rest, {\n href: absoluteHref || href,\n onClick: isExternal || reloadDocument ? onClick : handleClick,\n ref: ref,\n target: target\n }))\n );\n});\n\nif (process.env.NODE_ENV !== \"production\") {\n Link.displayName = \"Link\";\n}\n/**\n * A <Link> wrapper that knows if it's \"active\" or not.\n */\n\n\nconst NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef(_ref5, ref) {\n let {\n \"aria-current\": ariaCurrentProp = \"page\",\n caseSensitive = false,\n className: classNameProp = \"\",\n end = false,\n style: styleProp,\n to,\n children\n } = _ref5,\n rest = _objectWithoutPropertiesLoose(_ref5, _excluded2);\n\n let path = useResolvedPath(to, {\n relative: rest.relative\n });\n let location = useLocation();\n let routerState = React.useContext(UNSAFE_DataRouterStateContext);\n let {\n navigator\n } = React.useContext(UNSAFE_NavigationContext);\n let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;\n let locationPathname = location.pathname;\n let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;\n\n if (!caseSensitive) {\n locationPathname = locationPathname.toLowerCase();\n nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;\n toPathname = toPathname.toLowerCase();\n }\n\n let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(toPathname.length) === \"/\";\n let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === \"/\");\n let ariaCurrent = isActive ? ariaCurrentProp : undefined;\n let className;\n\n if (typeof classNameProp === \"function\") {\n className = classNameProp({\n isActive,\n isPending\n });\n } else {\n // If the className prop is not a function, we use a default `active`\n // class for <NavLink />s that are active. In v5 `active` was the default\n // value for `activeClassName`, but we are removing that API and can still\n // use the old default behavior for a cleaner upgrade path and keep the\n // simple styling rules working as they currently do.\n className = [classNameProp, isActive ? \"active\" : null, isPending ? \"pending\" : null].filter(Boolean).join(\" \");\n }\n\n let style = typeof styleProp === \"function\" ? styleProp({\n isActive,\n isPending\n }) : styleProp;\n return /*#__PURE__*/React.createElement(Link, _extends({}, rest, {\n \"aria-current\": ariaCurrent,\n className: className,\n ref: ref,\n style: style,\n to: to\n }), typeof children === \"function\" ? children({\n isActive,\n isPending\n }) : children);\n});\n\nif (process.env.NODE_ENV !== \"production\") {\n NavLink.displayName = \"NavLink\";\n}\n/**\n * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except\n * that the interaction with the server is with `fetch` instead of new document\n * requests, allowing components to add nicer UX to the page as the form is\n * submitted and returns with data.\n */\n\n\nconst Form = /*#__PURE__*/React.forwardRef((props, ref) => {\n return /*#__PURE__*/React.createElement(FormImpl, _extends({}, props, {\n ref: ref\n }));\n});\n\nif (process.env.NODE_ENV !== \"production\") {\n Form.displayName = \"Form\";\n}\n\nconst FormImpl = /*#__PURE__*/React.forwardRef((_ref6, forwardedRef) => {\n let {\n reloadDocument,\n replace,\n method = defaultMethod,\n action,\n onSubmit,\n fetcherKey,\n routeId,\n relative,\n preventScrollReset\n } = _ref6,\n props = _objectWithoutPropertiesLoose(_ref6, _excluded3);\n\n let submit = useSubmitImpl(fetcherKey, routeId);\n let formMethod = method.toLowerCase() === \"get\" ? \"get\" : \"post\";\n let formAction = useFormAction(action, {\n relative\n });\n\n let submitHandler = event => {\n onSubmit && onSubmit(event);\n if (event.defaultPrevented) return;\n event.preventDefault();\n let submitter = event.nativeEvent.submitter;\n let submitMethod = (submitter == null ? void 0 : submitter.getAttribute(\"formmethod\")) || method;\n submit(submitter || event.currentTarget, {\n method: submitMethod,\n replace,\n relative,\n preventScrollReset\n });\n };\n\n return /*#__PURE__*/React.createElement(\"form\", _extends({\n ref: forwardedRef,\n method: formMethod,\n action: formAction,\n onSubmit: reloadDocument ? onSubmit : submitHandler\n }, props));\n});\n\nif (process.env.NODE_ENV !== \"production\") {\n FormImpl.displayName = \"FormImpl\";\n}\n/**\n * This component will emulate the browser's scroll restoration on location\n * changes.\n */\n\n\nfunction ScrollRestoration(_ref7) {\n let {\n getKey,\n storageKey\n } = _ref7;\n useScrollRestoration({\n getKey,\n storageKey\n });\n return null;\n}\n\nif (process.env.NODE_ENV !== \"production\") {\n ScrollRestoration.displayName = \"ScrollRestoration\";\n} //#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region Hooks\n////////////////////////////////////////////////////////////////////////////////\n\n\nvar DataRouterHook;\n\n(function (DataRouterHook) {\n DataRouterHook[\"UseScrollRestoration\"] = \"useScrollRestoration\";\n DataRouterHook[\"UseSubmitImpl\"] = \"useSubmitImpl\";\n DataRouterHook[\"UseFetcher\"] = \"useFetcher\";\n})(DataRouterHook || (DataRouterHook = {}));\n\nvar DataRouterStateHook;\n\n(function (DataRouterStateHook) {\n DataRouterStateHook[\"UseFetchers\"] = \"useFetchers\";\n DataRouterStateHook[\"UseScrollRestoration\"] = \"useScrollRestoration\";\n})(DataRouterStateHook || (DataRouterStateHook = {}));\n\nfunction getDataRouterConsoleError(hookName) {\n return hookName + \" must be used within a data router. See https://reactrouter.com/routers/picking-a-router.\";\n}\n\nfunction useDataRouterContext(hookName) {\n let ctx = React.useContext(UNSAFE_DataRouterContext);\n !ctx ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;\n return ctx;\n}\n\nfunction useDataRouterState(hookName) {\n let state = React.useContext(UNSAFE_DataRouterStateContext);\n !state ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;\n return state;\n}\n/**\n * Handles the click behavior for router `<Link>` components. This is useful if\n * you need to create custom `<Link>` components with the same click behavior we\n * use in our exported `<Link>`.\n */\n\n\nfunction useLinkClickHandler(to, _temp) {\n let {\n target,\n replace: replaceProp,\n state,\n preventScrollReset,\n relative\n } = _temp === void 0 ? {} : _temp;\n let navigate = useNavigate();\n let location = useLocation();\n let path = useResolvedPath(to, {\n relative\n });\n return React.useCallback(event => {\n if (shouldProcessLinkClick(event, target)) {\n event.preventDefault(); // If the URL hasn't changed, a regular <a> will do a replace instead of\n // a push, so do the same here unless the replace prop is explicitly set\n\n let replace = replaceProp !== undefined ? replaceProp : createPath(location) === createPath(path);\n navigate(to, {\n replace,\n state,\n preventScrollReset,\n relative\n });\n }\n }, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative]);\n}\n/**\n * A convenient wrapper for reading and writing search parameters via the\n * URLSearchParams interface.\n */\n\nfunction useSearchParams(defaultInit) {\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(typeof URLSearchParams !== \"undefined\", \"You cannot use the `useSearchParams` hook in a browser that does not \" + \"support the URLSearchParams API. If you need to support Internet \" + \"Explorer 11, we recommend you load a polyfill such as \" + \"https://github.com/ungap/url-search-params\\n\\n\" + \"If you're unsure how to load polyfills, we recommend you check out \" + \"https://polyfill.io/v3/ which provides some recommendations about how \" + \"to load polyfills only for users that need them, instead of for every \" + \"user.\") : void 0;\n let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));\n let hasSetSearchParamsRef = React.useRef(false);\n let location = useLocation();\n let searchParams = React.useMemo(() => // Only merge in the defaults if we haven't yet called setSearchParams.\n // Once we call that we want those to take precedence, otherwise you can't\n // remove a param with setSearchParams({}) if it has an initial value\n getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current), [location.search]);\n let navigate = useNavigate();\n let setSearchParams = React.useCallback((nextInit, navigateOptions) => {\n const newSearchParams = createSearchParams(typeof nextInit === \"function\" ? nextInit(searchParams) : nextInit);\n hasSetSearchParamsRef.current = true;\n navigate(\"?\" + newSearchParams, navigateOptions);\n }, [navigate, searchParams]);\n return [searchParams, setSearchParams];\n}\n/**\n * Returns a function that may be used to programmatically submit a form (or\n * some arbitrary data) to the server.\n */\n\nfunction useSubmit() {\n return useSubmitImpl();\n}\n\nfunction useSubmitImpl(fetcherKey, routeId) {\n let {\n router\n } = useDataRouterContext(DataRouterHook.UseSubmitImpl);\n let defaultAction = useFormAction();\n return React.useCallback(function (target, options) {\n if (options === void 0) {\n options = {};\n }\n\n if (typeof document === \"undefined\") {\n throw new Error(\"You are calling submit during the server render. \" + \"Try calling submit within a `useEffect` or callback instead.\");\n }\n\n let {\n method,\n encType,\n formData,\n url\n } = getFormSubmissionInfo(target, defaultAction, options);\n let href = url.pathname + url.search;\n let opts = {\n replace: options.replace,\n preventScrollReset: options.preventScrollReset,\n formData,\n formMethod: method,\n formEncType: encType\n };\n\n if (fetcherKey) {\n !(routeId != null) ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"No routeId available for useFetcher()\") : UNSAFE_invariant(false) : void 0;\n router.fetch(fetcherKey, routeId, href, opts);\n } else {\n router.navigate(href, opts);\n }\n }, [defaultAction, router, fetcherKey, routeId]);\n}\n\nfunction useFormAction(action, _temp2) {\n let {\n relative\n } = _temp2 === void 0 ? {} : _temp2;\n let {\n basename\n } = React.useContext(UNSAFE_NavigationContext);\n let routeContext = React.useContext(UNSAFE_RouteContext);\n !routeContext ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"useFormAction must be used inside a RouteContext\") : UNSAFE_invariant(false) : void 0;\n let [match] = routeContext.matches.slice(-1); // Shallow clone path so we can modify it below, otherwise we modify the\n // object referenced by useMemo inside useResolvedPath\n\n let path = _extends({}, useResolvedPath(action ? action : \".\", {\n relative\n })); // Previously we set the default action to \".\". The problem with this is that\n // `useResolvedPath(\".\")` excludes search params and the hash of the resolved\n // URL. This is the intended behavior of when \".\" is specifically provided as\n // the form action, but inconsistent w/ browsers when the action is omitted.\n // https://github.com/remix-run/remix/issues/927\n\n\n let location = useLocation();\n\n if (action == null) {\n // Safe to write to these directly here since if action was undefined, we\n // would have called useResolvedPath(\".\") which will never include a search\n // or hash\n path.search = location.search;\n path.hash = location.hash; // When grabbing search params from the URL, remove the automatically\n // inserted ?index param so we match the useResolvedPath search behavior\n // which would not include ?index\n\n if (match.route.index) {\n let params = new URLSearchParams(path.search);\n params.delete(\"index\");\n path.search = params.toString() ? \"?\" + params.toString() : \"\";\n }\n }\n\n if ((!action || action === \".\") && match.route.index) {\n path.search = path.search ? path.search.replace(/^\\?/, \"?index&\") : \"?index\";\n } // If we're operating within a basename, prepend it to the pathname prior\n // to creating the form action. If this is a root navigation, then just use\n // the raw basename which allows the basename to have full control over the\n // presence of a trailing slash on root actions\n\n\n if (basename !== \"/\") {\n path.pathname = path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\nfunction createFetcherForm(fetcherKey, routeId) {\n let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => {\n return /*#__PURE__*/React.createElement(FormImpl, _extends({}, props, {\n ref: ref,\n fetcherKey: fetcherKey,\n routeId: routeId\n }));\n });\n\n if (process.env.NODE_ENV !== \"production\") {\n FetcherForm.displayName = \"fetcher.Form\";\n }\n\n return FetcherForm;\n}\n\nlet fetcherId = 0;\n/**\n * Interacts with route loaders and actions without causing a navigation. Great\n * for any interaction that stays on the same page.\n */\n\nfunction useFetcher() {\n var _route$matches;\n\n let {\n router\n } = useDataRouterContext(DataRouterHook.UseFetcher);\n let route = React.useContext(UNSAFE_RouteContext);\n !route ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"useFetcher must be used inside a RouteContext\") : UNSAFE_invariant(false) : void 0;\n let routeId = (_route$matches = route.matches[route.matches.length - 1]) == null ? void 0 : _route$matches.route.id;\n !(routeId != null) ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"useFetcher can only be used on routes that contain a unique \\\"id\\\"\") : UNSAFE_invariant(false) : void 0;\n let [fetcherKey] = React.useState(() => String(++fetcherId));\n let [Form] = React.useState(() => {\n !routeId ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"No routeId available for fetcher.Form()\") : UNSAFE_invariant(false) : void 0;\n return createFetcherForm(fetcherKey, routeId);\n });\n let [load] = React.useState(() => href => {\n !router ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"No router available for fetcher.load()\") : UNSAFE_invariant(false) : void 0;\n !routeId ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"No routeId available for fetcher.load()\") : UNSAFE_invariant(false) : void 0;\n router.fetch(fetcherKey, routeId, href);\n });\n let submit = useSubmitImpl(fetcherKey, routeId);\n let fetcher = router.getFetcher(fetcherKey);\n let fetcherWithComponents = React.useMemo(() => _extends({\n Form,\n submit,\n load\n }, fetcher), [fetcher, Form, submit, load]);\n React.useEffect(() => {\n // Is this busted when the React team gets real weird and calls effects\n // twice on mount? We really just need to garbage collect here when this\n // fetcher is no longer around.\n return () => {\n if (!router) {\n console.warn(\"No fetcher available to clean up from useFetcher()\");\n return;\n }\n\n router.deleteFetcher(fetcherKey);\n };\n }, [router, fetcherKey]);\n return fetcherWithComponents;\n}\n/**\n * Provides all fetchers currently on the page. Useful for layouts and parent\n * routes that need to provide pending/optimistic UI regarding the fetch.\n */\n\nfunction useFetchers() {\n let state = useDataRouterState(DataRouterStateHook.UseFetchers);\n return [...state.fetchers.values()];\n}\nconst SCROLL_RESTORATION_STORAGE_KEY = \"react-router-scroll-positions\";\nlet savedScrollPositions = {};\n/**\n * When rendered inside a RouterProvider, will restore scroll positions on navigations\n */\n\nfunction useScrollRestoration(_temp3) {\n let {\n getKey,\n storageKey\n } = _temp3 === void 0 ? {} : _temp3;\n let {\n router\n } = useDataRouterContext(DataRouterHook.UseScrollRestoration);\n let {\n restoreScrollPosition,\n preventScrollReset\n } = useDataRouterState(DataRouterStateHook.UseScrollRestoration);\n let location = useLocation();\n let matches = useMatches();\n let navigation = useNavigation(); // Trigger manual scroll restoration while we're active\n\n React.useEffect(() => {\n window.history.scrollRestoration = \"manual\";\n return () => {\n window.history.scrollRestoration = \"auto\";\n };\n }, []); // Save positions on pagehide\n\n usePageHide(React.useCallback(() => {\n if (navigation.state === \"idle\") {\n let key = (getKey ? getKey(location, matches) : null) || location.key;\n savedScrollPositions[key] = window.scrollY;\n }\n\n sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));\n window.history.scrollRestoration = \"auto\";\n }, [storageKey, getKey, navigation.state, location, matches])); // Read in any saved scroll locations\n\n if (typeof document !== \"undefined\") {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n try {\n let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);\n\n if (sessionPositions) {\n savedScrollPositions = JSON.parse(sessionPositions);\n }\n } catch (e) {// no-op, use default empty object\n }\n }, [storageKey]); // Enable scroll restoration in the router\n // eslint-disable-next-line react-hooks/rules-of-hooks\n\n React.useLayoutEffect(() => {\n let disableScrollRestoration = router == null ? void 0 : router.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKey);\n return () => disableScrollRestoration && disableScrollRestoration();\n }, [router, getKey]); // Restore scrolling when state.restoreScrollPosition changes\n // eslint-disable-next-line react-hooks/rules-of-hooks\n\n React.useLayoutEffect(() => {\n // Explicit false means don't do anything (used for submissions)\n if (restoreScrollPosition === false) {\n return;\n } // been here before, scroll to it\n\n\n if (typeof restoreScrollPosition === \"number\") {\n window.scrollTo(0, restoreScrollPosition);\n return;\n } // try to scroll to the hash\n\n\n if (location.hash) {\n let el = document.getElementById(location.hash.slice(1));\n\n if (el) {\n el.scrollIntoView();\n return;\n }\n } // Don't reset if this navigation opted out\n\n\n if (preventScrollReset === true) {\n return;\n } // otherwise go to the top on new locations\n\n\n window.scrollTo(0, 0);\n }, [location, restoreScrollPosition, preventScrollReset]);\n }\n}\n/**\n * Setup a callback to be fired on the window's `beforeunload` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\n\nfunction useBeforeUnload(callback, options) {\n let {\n capture\n } = options || {};\n React.useEffect(() => {\n let opts = capture != null ? {\n capture\n } : undefined;\n window.addEventListener(\"beforeunload\", callback, opts);\n return () => {\n window.removeEventListener(\"beforeunload\", callback, opts);\n };\n }, [callback, capture]);\n}\n/**\n * Setup a callback to be fired on the window's `pagehide` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes. This event is better supported than beforeunload across browsers.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\n\nfunction usePageHide(callback, options) {\n let {\n capture\n } = options || {};\n React.useEffect(() => {\n let opts = capture != null ? {\n capture\n } : undefined;\n window.addEventListener(\"pagehide\", callback, opts);\n return () => {\n window.removeEventListener(\"pagehide\", callback, opts);\n };\n }, [callback, capture]);\n}\n/**\n * Wrapper around useBlocker to show a window.confirm prompt to users instead\n * of building a custom UI with useBlocker.\n *\n * Warning: This has *a lot of rough edges* and behaves very differently (and\n * very incorrectly in some cases) across browsers if user click addition\n * back/forward navigations while the confirm is open. Use at your own risk.\n */\n\n\nfunction usePrompt(_ref8) {\n let {\n when,\n message\n } = _ref8;\n let blocker = unstable_useBlocker(when);\n React.useEffect(() => {\n if (blocker.state === \"blocked\" && !when) {\n blocker.reset();\n }\n }, [blocker, when]);\n React.useEffect(() => {\n if (blocker.state === \"blocked\") {\n let proceed = window.confirm(message);\n\n if (proceed) {\n setTimeout(blocker.proceed, 0);\n } else {\n blocker.reset();\n }\n }\n }, [blocker, message]);\n}\n //#endregion\n\nexport { BrowserRouter, Form, HashRouter, Link, NavLink, ScrollRestoration, useScrollRestoration as UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, usePrompt as unstable_usePrompt, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit };\n//# sourceMappingURL=index.js.map\n","import React from 'react';\nimport PropTypes from 'prop-types';\nimport { useTranslation } from 'react-i18next';\n\nimport { Button, ButtonGroup } from '@ohif/ui';\n\nfunction ActionButtons({ onExportClick, onCreateReportClick, disabled }) {\n const { t } = useTranslation('MeasurementTable');\n\n return (\n <React.Fragment>\n <Button\n className=\"text-base px-2 py-2\"\n size=\"initial\"\n variant={disabled ? 'disabled' : 'outlined'}\n color=\"black\"\n border=\"primaryActive\"\n onClick={onExportClick}\n disabled={disabled}\n >\n {t('Export')}\n </Button>\n <Button\n className=\"ml-2 px-2 text-base\"\n variant={disabled ? 'disabled' : 'outlined'}\n size=\"initial\"\n color=\"black\"\n border=\"primaryActive\"\n onClick={onCreateReportClick}\n disabled={disabled}\n >\n {t('Create Report')}\n </Button>\n </React.Fragment>\n );\n}\n\nActionButtons.propTypes = {\n onExportClick: PropTypes.func,\n onCreateReportClick: PropTypes.func,\n disabled: PropTypes.bool,\n};\n\nActionButtons.defaultProps = {\n onExportClick: () => alert('Export'),\n onCreateReportClick: () => alert('Create Report'),\n disabled: false,\n};\n\nexport default ActionButtons;\n","import React, { useEffect, useState, useRef } from 'react';\nimport PropTypes from 'prop-types';\nimport {\n StudySummary,\n MeasurementTable,\n Dialog,\n Input,\n useViewportGrid,\n} from '@ohif/ui';\nimport { DicomMetadataStore, utils } from '@ohif/core';\nimport { useDebounce } from '@hooks';\nimport ActionButtons from './ActionButtons';\nimport { useTrackedMeasurements } from '../../getContextModule';\nimport debounce from 'lodash.debounce';\n\nconst { downloadCSVReport } = utils;\nconst { formatDate } = utils;\n\nconst DISPLAY_STUDY_SUMMARY_INITIAL_VALUE = {\n key: undefined, //\n date: '', // '07-Sep-2010',\n modality: '', // 'CT',\n description: '', // 'CHEST/ABD/PELVIS W CONTRAST',\n};\n\nfunction PanelMeasurementTableTracking({ servicesManager, extensionManager }) {\n const [viewportGrid, viewportGridService] = useViewportGrid();\n const [measurementChangeTimestamp, setMeasurementsUpdated] = useState(\n Date.now().toString()\n );\n const debouncedMeasurementChangeTimestamp = useDebounce(\n measurementChangeTimestamp,\n 200\n );\n const {\n measurementService,\n uiDialogService,\n displaySetService,\n } = servicesManager.services;\n const [\n trackedMeasurements,\n sendTrackedMeasurementsEvent,\n ] = useTrackedMeasurements();\n const { trackedStudy, trackedSeries } = trackedMeasurements.context;\n const [displayStudySummary, setDisplayStudySummary] = useState(\n DISPLAY_STUDY_SUMMARY_INITIAL_VALUE\n );\n const [displayMeasurements, setDisplayMeasurements] = useState([]);\n const measurementsPanelRef = useRef(null);\n\n useEffect(() => {\n const measurements = measurementService.getMeasurements();\n const filteredMeasurements = measurements.filter(\n m =>\n trackedStudy === m.referenceStudyUID &&\n trackedSeries.includes(m.referenceSeriesUID)\n );\n\n const mappedMeasurements = filteredMeasurements.map(m =>\n _mapMeasurementToDisplay(\n m,\n measurementService.VALUE_TYPES,\n displaySetService\n )\n );\n setDisplayMeasurements(mappedMeasurements);\n // eslint-ignore-next-line\n }, [\n measurementService,\n trackedStudy,\n trackedSeries,\n debouncedMeasurementChangeTimestamp,\n ]);\n\n const updateDisplayStudySummary = async () => {\n if (trackedMeasurements.matches('tracking')) {\n const StudyInstanceUID = trackedStudy;\n const studyMeta = DicomMetadataStore.getStudy(StudyInstanceUID);\n const instanceMeta = studyMeta.series[0].instances[0];\n const { StudyDate, StudyDescription } = instanceMeta;\n\n const modalities = new Set();\n studyMeta.series.forEach(series => {\n if (trackedSeries.includes(series.SeriesInstanceUID)) {\n modalities.add(series.instances[0].Modality);\n }\n });\n const modality = Array.from(modalities).join('/');\n\n if (displayStudySummary.key !== StudyInstanceUID) {\n setDisplayStudySummary({\n key: StudyInstanceUID,\n date: StudyDate, // TODO: Format: '07-Sep-2010'\n modality,\n description: StudyDescription,\n });\n }\n } else if (trackedStudy === '' || trackedStudy === undefined) {\n setDisplayStudySummary(DISPLAY_STUDY_SUMMARY_INITIAL_VALUE);\n }\n };\n\n // ~~ DisplayStudySummary\n useEffect(() => {\n updateDisplayStudySummary();\n }, [\n displayStudySummary.key,\n trackedMeasurements,\n trackedStudy,\n updateDisplayStudySummary,\n ]);\n\n // TODO: Better way to consolidated, debounce, check on change?\n // Are we exposing the right API for measurementService?\n // This watches for ALL measurementService changes. It updates a timestamp,\n // which is debounced. After a brief period of inactivity, this triggers\n // a re-render where we grab up-to-date measurements\n useEffect(() => {\n const added = measurementService.EVENTS.MEASUREMENT_ADDED;\n const addedRaw = measurementService.EVENTS.RAW_MEASUREMENT_ADDED;\n const updated = measurementService.EVENTS.MEASUREMENT_UPDATED;\n const removed = measurementService.EVENTS.MEASUREMENT_REMOVED;\n const cleared = measurementService.EVENTS.MEASUREMENTS_CLEARED;\n const subscriptions = [];\n\n [added, addedRaw, updated, removed, cleared].forEach(evt => {\n subscriptions.push(\n measurementService.subscribe(evt, () => {\n setMeasurementsUpdated(Date.now().toString());\n if (evt === added) {\n debounce(() => {\n measurementsPanelRef.current.scrollTop =\n measurementsPanelRef.current.scrollHeight;\n }, 300)();\n }\n }).unsubscribe\n );\n });\n\n return () => {\n subscriptions.forEach(unsub => {\n unsub();\n });\n };\n }, [measurementService, sendTrackedMeasurementsEvent]);\n\n async function exportReport() {\n const measurements = measurementService.getMeasurements();\n const trackedMeasurements = measurements.filter(\n m =>\n trackedStudy === m.referenceStudyUID &&\n trackedSeries.includes(m.referenceSeriesUID)\n );\n\n downloadCSVReport(trackedMeasurements, measurementService);\n }\n\n const jumpToImage = ({ uid, isActive }) => {\n measurementService.jumpToMeasurement(viewportGrid.activeViewportIndex, uid);\n\n onMeasurementItemClickHandler({ uid, isActive });\n };\n\n const onMeasurementItemEditHandler = ({ uid, isActive }) => {\n const measurement = measurementService.getMeasurement(uid);\n jumpToImage({ uid, isActive });\n\n const onSubmitHandler = ({ action, value }) => {\n switch (action.id) {\n case 'save': {\n measurementService.update(\n uid,\n {\n ...measurement,\n ...value,\n },\n true\n );\n }\n }\n uiDialogService.dismiss({ id: 'enter-annotation' });\n };\n\n uiDialogService.create({\n id: 'enter-annotation',\n centralize: true,\n isDraggable: false,\n showOverlay: true,\n content: Dialog,\n contentProps: {\n title: 'Enter your annotation',\n noCloseButton: true,\n value: { label: measurement.label || '' },\n body: ({ value, setValue }) => {\n const onChangeHandler = event => {\n event.persist();\n setValue(value => ({ ...value, label: event.target.value }));\n };\n\n const onKeyPressHandler = event => {\n if (event.key === 'Enter') {\n onSubmitHandler({ value, action: { id: 'save' } });\n }\n };\n return (\n <div className=\"p-4 bg-primary-dark\">\n <Input\n autoFocus\n id=\"annotation\"\n className=\"mt-2 bg-black border-primary-main\"\n type=\"text\"\n containerClassName=\"mr-2\"\n value={value.label}\n onChange={onChangeHandler}\n onKeyPress={onKeyPressHandler}\n />\n </div>\n );\n },\n actions: [\n // temp: swap button types until colors are updated\n { id: 'cancel', text: 'Cancel', type: 'primary' },\n { id: 'save', text: 'Save', type: 'secondary' },\n ],\n onSubmit: onSubmitHandler,\n },\n });\n };\n\n const onMeasurementItemClickHandler = ({ uid, isActive }) => {\n if (!isActive) {\n const measurements = [...displayMeasurements];\n const measurement = measurements.find(m => m.uid === uid);\n\n measurements.forEach(m => (m.isActive = m.uid !== uid ? false : true));\n measurement.isActive = true;\n setDisplayMeasurements(measurements);\n }\n };\n\n const displayMeasurementsWithoutFindings = displayMeasurements.filter(\n dm => dm.measurementType !== measurementService.VALUE_TYPES.POINT\n );\n const additionalFindings = displayMeasurements.filter(\n dm => dm.measurementType === measurementService.VALUE_TYPES.POINT\n );\n\n return (\n <>\n <div\n className=\"overflow-x-hidden overflow-y-auto invisible-scrollbar\"\n ref={measurementsPanelRef}\n data-cy={'trackedMeasurements-panel'}\n >\n {displayStudySummary.key && (\n <StudySummary\n date={formatDate(displayStudySummary.date)}\n modality={displayStudySummary.modality}\n description={displayStudySummary.description}\n />\n )}\n <MeasurementTable\n title=\"Measurements\"\n data={displayMeasurementsWithoutFindings}\n servicesManager={servicesManager}\n onClick={jumpToImage}\n onEdit={onMeasurementItemEditHandler}\n />\n {additionalFindings.length !== 0 && (\n <MeasurementTable\n title=\"Additional Findings\"\n data={additionalFindings}\n servicesManager={servicesManager}\n onClick={jumpToImage}\n onEdit={onMeasurementItemEditHandler}\n />\n )}\n </div>\n <div className=\"flex justify-center p-4\">\n <ActionButtons\n onExportClick={exportReport}\n onCreateReportClick={() => {\n sendTrackedMeasurementsEvent('SAVE_REPORT', {\n viewportIndex: viewportGrid.activeViewportIndex,\n isBackupSave: true,\n });\n }}\n disabled={\n additionalFindings.length === 0 &&\n displayMeasurementsWithoutFindings.length === 0\n }\n />\n </div>\n </>\n );\n}\n\nPanelMeasurementTableTracking.propTypes = {\n servicesManager: PropTypes.shape({\n services: PropTypes.shape({\n measurementService: PropTypes.shape({\n getMeasurements: PropTypes.func.isRequired,\n VALUE_TYPES: PropTypes.object.isRequired,\n }).isRequired,\n }).isRequired,\n }).isRequired,\n};\n\n// TODO: This could be a measurementService mapper\nfunction _mapMeasurementToDisplay(measurement, types, displaySetService) {\n const { referenceStudyUID, referenceSeriesUID, SOPInstanceUID } = measurement;\n\n // TODO: We don't deal with multiframe well yet, would need to update\n // This in OHIF-312 when we add FrameIndex to measurements.\n\n const instance = DicomMetadataStore.getInstance(\n referenceStudyUID,\n referenceSeriesUID,\n SOPInstanceUID\n );\n\n const displaySets = displaySetService.getDisplaySetsForSeries(\n referenceSeriesUID\n );\n\n if (!displaySets[0] || !displaySets[0].images) {\n throw new Error(\n 'The tracked measurements panel should only be tracking \"stack\" displaySets.'\n );\n }\n\n const {\n displayText: baseDisplayText,\n uid,\n label: baseLabel,\n type,\n selected,\n findingSites,\n finding,\n } = measurement;\n\n const firstSite = findingSites?.[0];\n const label = baseLabel || finding?.text || firstSite?.text || '(empty)';\n let displayText = baseDisplayText || [];\n if (findingSites) {\n const siteText = [];\n findingSites.forEach(site => {\n if (site?.text !== label) siteText.push(site.text);\n });\n displayText = [...siteText, ...displayText];\n }\n if (finding && finding?.text !== label) {\n displayText = [finding.text, ...displayText];\n }\n\n return {\n uid,\n label,\n baseLabel,\n measurementType: type,\n displayText,\n baseDisplayText,\n isActive: selected,\n finding,\n findingSites,\n };\n}\n\nexport default PanelMeasurementTableTracking;\n","import { useState, useEffect } from 'react';\n\n/**\n * See: https://usehooks.com/useDebounce/\n *\n * @param {*} value\n * @param {number} delay - delat in ms\n */\nexport default function useDebounce(value, delay) {\n // State and setters for debounced value\n const [debouncedValue, setDebouncedValue] = useState(value);\n\n useEffect(\n () => {\n // Update debounced value after delay\n const handler = setTimeout(() => {\n setDebouncedValue(value);\n }, delay);\n\n // Cancel the timeout if value changes (also on delay change or unmount)\n // This is how we prevent debounced value from updating if value is changed ...\n // .. within the delay period. Timeout gets cleared and restarted.\n return () => {\n clearTimeout(handler);\n };\n },\n [value, delay] // Only re-call effect if value or delay changes\n );\n\n return debouncedValue;\n}\n","import { Types } from '@ohif/core';\nimport {\n PanelMeasurementTableTracking,\n PanelStudyBrowserTracking,\n} from './panels';\n\n// TODO:\n// - No loading UI exists yet\n// - cancel promises when component is destroyed\n// - show errors in UI for thumbnails if promise fails\nfunction getPanelModule({\n commandsManager,\n extensionManager,\n servicesManager,\n}): Types.Panel[] {\n return [\n {\n name: 'seriesList',\n iconName: 'group-layers',\n iconLabel: 'Studies',\n label: 'Studies',\n component: PanelStudyBrowserTracking.bind(null, {\n commandsManager,\n extensionManager,\n servicesManager,\n }),\n },\n\n {\n name: 'trackedMeasurements',\n iconName: 'tab-linear',\n iconLabel: 'Measure',\n label: 'Measurements',\n component: PanelMeasurementTableTracking.bind(null, {\n commandsManager,\n extensionManager,\n servicesManager,\n }),\n },\n ];\n}\n\nexport default getPanelModule;\n","import React from 'react';\n\nconst Component = React.lazy(() => {\n return import(\n /* webpackPrefetch: true */ './viewports/TrackedCornerstoneViewport'\n );\n});\n\nconst OHIFCornerstoneViewport = props => {\n return (\n <React.Suspense fallback={<div>Loading...</div>}>\n <Component {...props} />\n </React.Suspense>\n );\n};\n\nfunction getViewportModule({\n servicesManager,\n commandsManager,\n extensionManager,\n}) {\n const ExtendedOHIFCornerstoneTrackingViewport = props => {\n return (\n <OHIFCornerstoneViewport\n servicesManager={servicesManager}\n commandsManager={commandsManager}\n extensionManager={extensionManager}\n {...props}\n />\n );\n };\n\n return [\n {\n name: 'cornerstone-tracked',\n component: ExtendedOHIFCornerstoneTrackingViewport,\n },\n ];\n}\n\nexport default getViewportModule;\n","import getContextModule from './getContextModule';\nimport getPanelModule from './getPanelModule';\nimport getViewportModule from './getViewportModule';\nimport { id } from './id.js';\n\nconst measurementTrackingExtension = {\n /**\n * Only required property. Should be a unique value across all extensions.\n */\n id,\n\n getContextModule,\n getPanelModule,\n getViewportModule,\n};\n\nexport default measurementTrackingExtension;\n","import packageJson from '../package.json';\n\nconst id = packageJson.name;\n\nexport { id };\n"],"names":["root","factory","exports","module","require","define","amd","globalThis","__WEBPACK_EXTERNAL_MODULE__369__","__WEBPACK_EXTERNAL_MODULE__762__","__WEBPACK_EXTERNAL_MODULE__148__","__WEBPACK_EXTERNAL_MODULE__867__","__WEBPACK_EXTERNAL_MODULE__464__","deferred","leafPrototypes","getProto","installedChunks","__assign","this","Object","assign","t","s","i","n","arguments","length","p","prototype","hasOwnProperty","call","apply","__rest","e","indexOf","getOwnPropertySymbols","propertyIsEnumerable","__read","o","m","Symbol","iterator","r","ar","next","done","push","value","error","defineProperty","react_1","xstate_1","defaultOptions","immediate","useMachine","machine","options","context","guards","actions","activities","services","delays","rehydratedState","state","interpreterOptions","machineConfig","machineRef","useRef","current","withConfig","serviceRef","interpret","onTransition","changed","setCurrent","service","useEffect","initialState","State","create","_a","useState","start","undefined","stop","send","useService","sub","subscribe","unsubscribe","useActor_1","useActor","actor","actorRef","sub_1","RESPONSE","machineConfiguration","id","initial","trackedStudy","trackedSeries","ignoredSeries","prevTrackedStudy","prevTrackedSeries","prevIgnoredSeries","ignoredSRSeriesForHydration","isDirty","states","off","type","idle","entry","on","TRACK_SERIES","SET_TRACKED_SERIES","target","PROMPT_HYDRATE_SR","cond","RESTORE_PROMPT_HYDRATE_SR","HYDRATE_SR","promptBeginTracking","invoke","src","onDone","onError","tracking","UNTRACK_SERIES","SAVE_REPORT","SET_DIRTY","promptTrackNewSeries","promptTrackNewStudy","promptSaveReport","promptHydrateStructuredReport","hydrateStructuredReport","strict","ctx","evt","discardPreviouslyTrackedMeasurements","console","log","clearAllMeasurements","jumpToFirstMeasurementInActiveViewport","warn","showStructuredReportDisplaySetInActiveViewport","clearContext","setTrackedStudyAndSeries","slice","data","StudyInstanceUID","SeriesInstanceUID","setTrackedStudyAndMultipleSeries","studyInstanceUID","seriesInstanceUIDs","SeriesInstanceUIDs","setIsDirtyToClean","setIsDirty","ignoreSeries","ignoreHydrationForSRSeries","srSeriesInstanceUID","addTrackedSeries","removeTrackedSeries","filter","ser","shouldSetDirty","includes","shouldKillMachine","userResponse","shouldAddSeries","shouldSetStudyAndSeries","shouldAddIgnoredSeries","shouldPromptSaveReport","shouldIgnoreHydrationForSR","shouldSaveAndContinueWithSameReport","isBackupSave","shouldSaveAndStartNewReport","shouldHydrateStructuredReport","hasRemainingTrackedSeries","hasNotIgnoredSRSeriesForHydration","isNewStudy","isNewSeries","NO_NEVER","CANCEL","CREATE_REPORT","ADD_SERIES","SET_STUDY_AND_SERIES","_ref","servicesManager","extensionManager","uiViewportDialogService","viewportIndex","Promise","async","resolve","reject","promptResult","message","text","onSubmit","result","hide","show","onOutsideClick","_askTrackMeasurements","NO_NOT_FOR_SERIES","UIViewportDialogService","_askShouldAddMeasurements","_askSaveDiscardOrCancel","Loading","React","className","commandsManager","dataSource","measurements","displaySetService","uiNotificationService","uiDialogService","loadingDialogId","showOverlay","isDraggable","centralize","content","naturalizedReport","runCommand","measurementData","additionalFindingTypes","DicomMetadataStore","displaySetInstanceUID","getMostRecentDisplaySet","title","dismiss","MIN_SR_SERIES_NUMBER","measurementService","displaySetInstanceUIDs","dialogId","Dialog","useLastPosition","contentProps","label","noCloseButton","onClose","_handleClose","action","body","_ref2","setValue","Input","autoFocus","containerClassName","onChange","event","persist","onKeyPress","key","createReportDialogPrompt","getDataSources","trackedMeasurements","getMeasurements","referenceStudyUID","referenceSeriesUID","SeriesDescription","SeriesNumber","srSeriesNumbers","getActiveDisplaySets","ds","Modality","map","Math","max","getNextSRSeriesNumber","createReportAsync","createdDisplaySetInstanceUIDs","HYDRATE_REPORT","srDisplaySet","getDisplaySetByUID","hydrationResult","baseHydrateStructuredReport","TrackedMeasurementsContext","displayName","useTrackedMeasurements","useContext","SR_SOPCLASSHANDLERID","TrackedMeasurementsContextProvider","children","viewportGrid","viewportGridService","useViewportGrid","activeViewportIndex","viewports","machineOptions","referencedDisplaySetUID","referencedImages","images","isVolumeIdReferenced","imageId","startsWith","imageIndex","findIndex","image","imageIdToUse","keys","substring","setDisplaySetsForViewport","viewportOptions","initialImageOptions","index","StructuredReportDisplaySetInstanceUID","measurementIds","ms","fm","remove","uid","measurementTrackingMachine","Machine","sendTrackedMeasurementsEvent","trackedMeasurementsService","activeViewport","displaySet","SOPClassHandlerId","isLoaded","load","isRehydratable","Provider","propTypes","PropTypes","BoundTrackedMeasurementsContextProvider","bind","name","provider","formatDate","utils","TrackedCornerstoneViewport","props","displaySets","viewportLabel","useTranslation","cornerstoneViewportService","isTracked","setIsTracked","trackedMeasurementUID","setTrackedMeasurementUID","viewportElem","setViewportElem","viewportId","SeriesDate","PatientID","PatientName","PatientSex","PatientAge","SliceThickness","SpacingBetweenSlices","ManufacturerModelName","updateIsTracked","useCallback","viewport","getCornerstoneViewportByIndex","BaseVolumeViewport","currentImageId","getCurrentImageId","onElementEnabled","detail","element","addEventListener","Enums","onElementDisabled","removeEventListener","EVENTS","VIEWPORT_DATA_CHANGED","annotation","global","lineDash","getRenderingEngine","renderViewport","ViewportActionBar","onDoubleClick","stopPropagation","preventDefault","useAltStyling","onArrowsClick","direction","newTrackedMeasurementUID","trackedMeasurementId","getState","activeViewportDisplaySetInstanceUIDs","filteredMeasurements","measurementCount","uids","measurementIndex","_getNextMeasurementUID","jumpToMeasurement","switchMeasurement","getStatusComponent","trackedIcon","Tooltip","position","Icon","_getStatusComponent","studyData","studyDate","currentSeries","seriesDescription","patientInformation","patientName","OHIF","patientSex","patientAge","MRN","thickness","parseFloat","toFixed","spacing","scanner","getCornerstoneViewport","component","Component","getModuleEntry","_extends","isRequired","customProps","defaultProps","NAN","symbolTag","reTrim","reIsBadHex","reIsBinary","reIsOctal","freeParseInt","parseInt","freeGlobal","g","freeSelf","self","Function","objectToString","toString","nativeMax","nativeMin","min","now","Date","isObject","toNumber","isObjectLike","isSymbol","other","valueOf","replace","isBinary","test","func","wait","lastArgs","lastThis","maxWait","timerId","lastCallTime","lastInvokeTime","leading","maxing","trailing","TypeError","invokeFunc","time","args","thisArg","shouldInvoke","timeSinceLastCall","timerExpired","trailingEdge","setTimeout","remainingWait","debounced","isInvoking","leadingEdge","cancel","clearTimeout","flush","propIsEnumerable","test1","String","getOwnPropertyNames","test2","fromCharCode","join","test3","split","forEach","letter","err","shouldUseNative","source","from","symbols","to","val","toObject","ReactPropTypesSecret","emptyFunction","emptyFunctionWithReset","resetWarningCache","shim","propName","componentName","location","propFullName","secret","Error","getShim","ReactPropTypes","array","bigint","bool","number","object","string","symbol","any","arrayOf","elementType","instanceOf","node","objectOf","oneOf","oneOfType","shape","exact","checkPropTypes","l","Fragment","StrictMode","Profiler","q","Suspense","u","v","for","w","x","z","a","b","c","encodeURIComponent","A","isMounted","enqueueForceUpdate","enqueueReplaceState","enqueueSetState","B","C","refs","updater","D","E","isReactComponent","setState","forceUpdate","F","constructor","isPureReactComponent","G","H","I","ref","__self","__source","J","d","k","h","f","Array","$$typeof","_owner","L","M","N","escape","O","isArray","K","y","P","Q","_status","_result","then","default","R","S","T","ReactCurrentDispatcher","ReactCurrentBatchConfig","transition","ReactCurrentOwner","IsSomeRendererActing","Children","count","toArray","only","PureComponent","__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED","cloneElement","createContext","_calculateChangedBits","_currentValue","_currentValue2","_threadCount","Consumer","_context","createElement","createFactory","createRef","forwardRef","render","isValidElement","lazy","_payload","_init","memo","compare","useDebugValue","useImperativeHandle","useLayoutEffect","useMemo","useReducer","version","ActionTypes","SpecialTargets","__spreadArray","pack","concat","Start","Stop","raise","Raise","Send","Cancel","nullEvent","NullEvent","Assign","after","After","doneState","DoneState","Log","init","Init","Invoke","errorExecution","ErrorExecution","errorPlatform","ErrorPlatform","ErrorCustom","update","Update","choose","Choose","pure","Pure","STATE_DELIMITER","EMPTY_ACTIVITY_MAP","DEFAULT_GUARD_TYPE","IS_PRODUCTION","matchesState","parentStateId","childStateId","delimiter","parentStateValue","toStateValue","childStateValue","isString","every","getEventType","toStatePath","stateId","stateValue","pathToStateValue","statePath","marker","mapValues","collection","iteratee","collectionKeys","mapFilterValues","predicate","e_1","_b","_c","item","e_1_1","return","path","e_2","props_1","props_1_1","e_2_1","toStatePaths","flatten","subStateValue","subPath","toArrayStrict","mapContext","mapper","_event","e_5","isFunction","subMapper","e_5_1","isPromiseLike","updateHistoryStates","hist","subHist","updateContext","assignActions","updatedContext","reduce","acc","assignAction","e_7","assignment","meta","partialUpdate","propAssignment","e_7_1","toGuard","condition","guardMap","symbolObservable","observable","isMachine","uniqueId","currentId","toEventObject","payload","toSCXMLEvent","scxmlEvent","$$type","eventObject","toTransitionConfigArray","configLike","transitionLike","evaluateGuard","guard","guardMeta","condFn","toInvokeSource","toObserver","nextHandler","errorHandler","completionHandler","noop","isObserver","complete","createInvokeId","stateNodeId","isRaisableAction","Internal","delay","initEvent","getActionFunction","actionType","actionFunctionMap","toActionObject","actionObject","exec","toActionObjects","subAction","toActivityDefinition","resolveRaise","delaysMap","resolvedDelay","resolvedEvent","configDelay","resolveSend","resolvedTarget","sendParent","Parent","sendTo","sendUpdate","respond","_","__","origin","defaultLogExpr","expr","resolveLog","sendId","activity","activityDef","resolveStop","actorRefOrString","resolvedActorRef","isActionObject","delayRef","idSuffix","DoneInvoke","getActions","get","forwardTo","originalTarget_1","_i","escalate","errorData","conds","pluckAssigns","actionBlocks","actionBlocks_1","actionBlocks_1_1","block","splice","resolveActions","currentState","currentContext","predictableExec","preserveActionOrder","preservedContexts","deferredToBlockEnd","handleAction","blockType","raisedAction","sendAction","configuredDelay","resolved","matchedActions","find","resolvedActionsFromChoose","resolvedContextFromChoose","resolvedActionsFromPure","resolvedContext","resolvedActionObject","exec_1","contextIndex_1","wrapped","_ctx","resolvedActions","serviceStack","provide","fn","pop","consume","createNullActor","getSnapshot","toJSON","createDeferredActor","entity","tempActor","initialState_1","withContext","toActorRef","actorRefLike","isLeafNode","stateNode","getAllChildren","getChildren","sn","getAllStateNodes","stateNodes","getConfiguration","prevStateNodes","e_3","e_4","_d","prevAdjList","getAdjList","Set","configuration","configuration_1","configuration_1_1","parent","has","add","adjList","configuration_2","configuration_2_1","_e","_f","child","initialStateNodes","e_3_1","configuration_3","configuration_3_1","e_4_1","getValueFromAdj","baseNode","childStateNodes","childStateNode","csn","Map","configuration_4","configuration_4_1","set","getValue","rootNode","iterable","some","member","isInFinalState","getTagsFromConfiguration","tags","stateValuesEqual","aKeys","bKeys","isStateConfig","config","_this","events","_sessionid","historyValue","history","matches","toStrings","transitions","ownEvents","nextEvents","inert","valueKeys","jsonValues","hasTag","tag","can","transitionData","getTransitionData","deferEvents","Scheduler","processingEvent","queue","initialized","initialize","callback","schedule","process","flushEvents","task","clear","nextCallback","shift","sessionIdIndex","registry","delete","getGlobal","window","registerService","devTools","__xstate__","getDevTools","register","spawnBehavior","behavior","observers","mailbox","flushing","event_1","actorCtx","observer","handleError","InterpreterStatus","DEFAULT_SPAWN_OPTIONS","sync","autoForward","Interpreter","delayedEventsMap","listeners","contextListeners","stopListeners","doneListeners","eventListeners","sendListeners","status","NotStarted","_outgoingQueue","batch","Stopped","JSON","stringify","Running","scheduler","forward","nextState","_nextState","_state","isParent","sessionId","predictableActionArguments","_exec","actionOrExec","sendAction_1","defer","invokeSource","serviceCreator","resolvedData","spawn","spawnActivity","stopChild","logger","resolvedOptions","clock","resolvedId","_initialState","enumerable","configurable","execute","actionsConfig","listener","_g","_h","_j","_k","contextListener","finalChildStateNode","doneData","_doneEvent","_l","_m","_stop","_stopChildren","nextListenerOrObserver","completeListener","completeOnce","onStop","onEvent","onSend","resolvedState","resolveState","attachDev","e_6","e_8","e_9","e_10","e_6_1","e_8_1","_o","e_9_1","_p","_q","e_10_1","exitActions","sort","order","onExit","newState","e_11","batchChanged","batchedActions","_loop_1","bindActionToState","events_1","events_1_1","e_11_1","sender","nextEvent","e_12","e_12_1","removeChild","childId","spawnPromise","spawnCallback","spawnActor","isObservable","spawnObservable","spawnMachine","childService","doneEvent","promise","canceled","response","errorEvent","originalError","currentError","originalStackTrace","stack","stackTrace","reportUnhandledExceptionOnInvocation","unsubscribed","emitted","callbackStop","receivers","newListener","receiver","subscription","implementation","dispose","spawnEffect","__REDUX_DEVTOOLS_EXTENSION__","devToolsOptions","connect","autoPause","stateSanitizer","features","jump","skip","resolveSpawnOptions","nameOrOptions","isLazyEntity","simpleSrc","toInvokeDefinition","invokeConfig","invokeDef","NULL_EVENT","WILDCARD","EMPTY_OBJECT","isStateId","str","StateNode","_stateInfo","__xstatenode","__cache","relativeValue","initialStateValue","candidates","delayedTransitions","idMap","parallel","schema","description","stateConfig","dfs","_transient","always","onEntry","exit","invokeId","definition","eventType","getDelayedTransitions","formatTransitions","getCandidates","eventName","transient","sameEventType","afterConfig","mutateEntryExit","configTransition","resolvedTransition","isNaN","delayedTransition","formatTransition","getStateNodes","getStateNode","subStateKeys","subStateNodes","subStateKey","handles","stateFromConfig","transitionLeafNode","transitionCompoundNode","_transition","transitionParallelNode","transitionMap","stateTransitions","enabledTransitions","st","exitSet","selectedTransition","nextStateNodes","candidate","stateIn","in","isInState","getStateNodeById","guardPassed","allNextStateNodes","getRelativeStateNodes","internal","targetNode","getPotentiallyReenteringNodes","nodes","possibleAncestor","resolvedConfig","isDone","prevState","prevConfig","entrySet","prevConfig_1","prevConfig_1_1","entryStates","exitStates","doneEvents","grandparent","parentNode","entryActions","invokeActions","stopActions","resolvedStateValue","getResolvedPath","stateTransition","resolveTransition","resolveRaisedTransition","originalEvent","currentActions","unshift","willTransition","resolvedConfiguration","items","truthy","falsy","items_1","items_1_1","partition","raisedEvents","nonRaisedActions","invokeDefinition","invokeSrc","createInvocableActor","didUpdateContext","hasAlwaysTransitions","maybeNextState","raisedEvent","stateKey","resolvedStateId","STATE_IDENTIFIER","getStateNodeByPath","arrayStatePath","currentStateNode","subStateNode","stateIdentifier","getInitialState","historyConfig","relativeStateId","resolveHistory","initialPath","getFromRelativePath","relativePath","childStatePath","relativeStateValue","historyTarget","relativeChildPath","accessorProp","subHistoryValue","props_2","props_2_1","prop","subStatePath","childStateIds","stateIds","resolveTarget","_target","isInternalTarget","transitionConfig","normalizedTarget","normalizeTarget","onConfig","wildcardConfigs","strictTransitionConfigs_1","transitionConfigArray","hasNonLastUnguardedTarget","eventText","validateArrayifiedTransitions","eventlessConfig","doneConfig","settleTransitions","formattedTransitions","delayedTransitions_1","delayedTransitions_1_1","warned","initialContext","createMachine","mapState","stateMap","foundStateId","mappedStateId","matchState","patterns","defaultValue","patterns_1","patterns_1_1","createSchema","obj","_toPropertyKey","arg","input","hint","prim","toPrimitive","res","Number","writable","_console","_len","_key","alreadyWarned","_len2","_key2","loadNamespaces","i18n","ns","cb","isInitialized","matchHtmlEntity","htmlEntities","unescapeHtmlEntity","i18nInstance","bindI18n","bindI18nStore","transEmptyNodeValue","transSupportBasicHtmlNodes","transWrapTextNodes","transKeepBasicHtmlNodesFor","useSuspense","unescape","_defineProperties","descriptor","ReportNamespaces","instance","Constructor","_classCallCheck","usedNamespaces","protoProps","staticProps","namespaces","_arrayLikeToArray","arr","len","arr2","_s","_x","_r","_arr","_n","minLen","enumerableOnly","sym","getOwnPropertyDescriptor","getOwnPropertyDescriptors","defineProperties","usePrevious","ignore","i18nFromProps","i18nFromContext","defaultNSFromContext","defaultNS","reportNamespaces","notReadyT","optsOrDefaultValue","retNotReady","ready","react","i18nOptions","keyPrefix","addUsedNamespaces","initializedStoreOnce","languages","ignoreJSONStructure","hasLoadedNamespace","precheck","loadNotPending","backendConnector","backend","isLanguageChangingTo","lng","fallbackLng","lastLng","toLowerCase","loadState","hasResourceBundle","resources","partialBundledLanguages","oldI18nextHasLoadedNamespace","getT","getFixedT","nsMode","_useState2","setT","joinedNS","previousJoinedNS","boundReset","store","isInitial","ret","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","chunkIds","priority","notFulfilled","Infinity","fulfilled","j","chunkId","getter","__esModule","getPrototypeOf","mode","def","toStringTag","link","document","nc","setAttribute","rel","as","href","head","appendChild","PanelStudyBrowserTracking","getImageSrc","getStudiesForPatientByMRN","requestDisplaySetCreationForStudy","hangingProtocolService","StudyInstanceUIDs","useImageViewer","numCols","numRows","activeTabName","setActiveTabName","expandedStudyInstanceUIDs","setExpandedStudyInstanceUIDs","studyDisplayList","setStudyDisplayList","setDisplaySets","thumbnailImageSrcMap","setThumbnailImageSrcMap","jumpToDisplaySet","setJumpToDisplaySet","added","MEASUREMENT_ADDED","addedRaw","RAW_MEASUREMENT_ADDED","subscriptions","measurement","unsub","sid","qidoForStudyUID","query","studies","search","studyInstanceUid","qidoStudiesForPatient","actuallyMappedStudies","study","AccessionNumber","accession","StudyDate","date","StudyDescription","NumInstances","instances","ModalitiesInStudy","modalities","mrn","StudyTime","qidoStudy","numInstances","prevArray","it","fetchStudiesForPatient","currentDisplaySets","activeDisplaySets","newImageSrcEntry","dSet","imageIds","getImageIdsForDisplaySet","floor","mappedDisplaySets","_mapDisplaySets","SubscriptionDisplaySetsAdded","DISPLAY_SETS_ADDED","displaySetsAdded","madeInClient","SubscriptionDisplaySetsChanged","DISPLAY_SETS_CHANGED","changedDisplaySets","tabs","primaryStudyInstanceUIDs","primaryStudies","recentStudies","allStudies","displaySetsForStudy","dsSortFn","getDisplaySetSortFunction","tabStudy","_byDate","dateA","parse","studyA","studyB","_createStudyBrowserTabs","getElementById","scrollIntoView","thumbnailLocation","tabName","_findTabAndStudyOfDisplaySet","updatedExpandedStudyInstanceUIDs","StudyBrowser","onClickStudy","shouldCollapseStudy","stdyUid","onClickTab","clickedTabName","onClickUntrack","onClickThumbnail","onDoubleClickThumbnail","updatedViewports","getViewportsRequireUpdate","duration","setDisplaySetsForViewports","activeDisplaySetInstanceUIDs","trackedSeriesInstanceUIDs","thumbnailDisplaySets","thumbnailNoImageDisplaySets","excludeFromThumbnailBrowser","imageSrc","componentType","thumbnailNoImageModalities","_getComponentType","numPanes","getNumViewportPanes","viewportIdentificator","viewportData","thumbnailProps","seriesNumber","modality","seriesDate","numImageFrames","countIcon","dragData","series","canReject","onReject","classes","onShow","querySelector","focus","_ref3","deleteDisplaySet","cornerstone","canvas","utilities","loadImageToCanvas","toDataURL","catch","retrieve","metadata","WrappedPanelStudyBrowserTracking","getActiveDataSource","utilityModule","_getStudyForPatientUtility","_getStudiesForPatientByMRN","_getImageSrcFromImageId","getCornerstoneLibraries","getImageSrcFromImageId","ex","_createGetImageSrcFromImageIdFn","_requestDisplaySetCreationForStudy","Action","ResultType","validMutationMethodsArr","validRequestMethodsArr","is","checkIfSnapshotChanged","inst","latestGetSnapshot","prevValue","nextValue","RenderErrorBoundary","super","static","componentDidCatch","errorInfo","RouteContext","routeContext","RouteErrorContext","DataRouterHook","DataRouterStateHook","AwaitRenderStatus","AwaitErrorBoundary","errorElement","pending","renderError","_tracked","_error","_data","success","AbortedDeferredError","neverSettledPromise","AwaitContext","ActionButtons","onExportClick","onCreateReportClick","disabled","Button","size","variant","color","border","onClick","alert","downloadCSVReport","DISPLAY_STUDY_SUMMARY_INITIAL_VALUE","PanelMeasurementTableTracking","measurementChangeTimestamp","setMeasurementsUpdated","debouncedMeasurementChangeTimestamp","debouncedValue","setDebouncedValue","handler","useDebounce","displayStudySummary","setDisplayStudySummary","displayMeasurements","setDisplayMeasurements","measurementsPanelRef","mappedMeasurements","types","SOPInstanceUID","getDisplaySetsForSeries","displayText","baseDisplayText","baseLabel","selected","findingSites","finding","firstSite","siteText","site","measurementType","isActive","_mapMeasurementToDisplay","VALUE_TYPES","updateDisplayStudySummary","studyMeta","instanceMeta","updated","MEASUREMENT_UPDATED","removed","MEASUREMENT_REMOVED","cleared","MEASUREMENTS_CLEARED","debounce","scrollTop","scrollHeight","jumpToImage","onMeasurementItemClickHandler","onMeasurementItemEditHandler","getMeasurement","onSubmitHandler","_ref4","_ref5","_ref6","displayMeasurementsWithoutFindings","dm","POINT","additionalFindings","StudySummary","MeasurementTable","onEdit","iconName","iconLabel","OHIFCornerstoneViewport","fallback","packageJson","getContextModule","getPanelModule","getViewportModule"],"sourceRoot":""}
|