{"version":3,"file":"pyne-widget.umd.js","sources":["../node_modules/react/cjs/react.production.min.js","../node_modules/react/index.js","../node_modules/scheduler/cjs/scheduler.production.min.js","../node_modules/scheduler/index.js","../node_modules/react-dom/cjs/react-dom.production.min.js","../node_modules/react-dom/index.js","../node_modules/react-dom/client.js","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/react/jsx-runtime.js","../node_modules/mobx/dist/mobx.esm.js","../node_modules/mobx-react-lite/es/utils/assertEnvironment.js","../node_modules/mobx-react-lite/es/utils/observerBatching.js","../node_modules/mobx-react-lite/es/utils/printDebugValue.js","../node_modules/mobx-react-lite/es/utils/UniversalFinalizationRegistry.js","../node_modules/mobx-react-lite/es/utils/observerFinalizationRegistry.js","../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.min.js","../node_modules/use-sync-external-store/shim/index.js","../node_modules/mobx-react-lite/es/useObserver.js","../node_modules/mobx-react-lite/es/observer.js","../node_modules/mobx-react-lite/es/useAsObservableSource.js","../node_modules/mobx-react-lite/es/index.js","../src/lib/log.ts","../src/api/ping.ts","../src/lib/SyncManager.ts","../node_modules/mitt/dist/mitt.mjs","../src/lib/events/baseEventEmitter.ts","../src/lib/events/eventBus.ts","../src/lib/tracking/onPageChange.ts","../src/lib/tracking/EventBuffer.ts","../node_modules/tslib/tslib.es6.mjs","../node_modules/ts-invariant/lib/invariant.js","../node_modules/clsx/dist/clsx.m.js","../node_modules/tailwind-merge/dist/lib/tw-join.mjs","../node_modules/tailwind-merge/dist/lib/class-utils.mjs","../node_modules/tailwind-merge/dist/lib/lru-cache.mjs","../node_modules/tailwind-merge/dist/lib/modifier-utils.mjs","../node_modules/tailwind-merge/dist/lib/config-utils.mjs","../node_modules/tailwind-merge/dist/lib/merge-classlist.mjs","../node_modules/tailwind-merge/dist/lib/create-tailwind-merge.mjs","../node_modules/tailwind-merge/dist/lib/from-theme.mjs","../node_modules/tailwind-merge/dist/lib/validators.mjs","../node_modules/tailwind-merge/dist/lib/default-config.mjs","../node_modules/uuid/dist/esm-browser/stringify.js","../node_modules/tailwind-merge/dist/lib/tw-merge.mjs","../node_modules/uuid/dist/esm-browser/rng.js","../node_modules/uuid/dist/esm-browser/native.js","../node_modules/uuid/dist/esm-browser/v4.js","../src/lib/utils.ts","../src/lib/tracking/track.ts","../src/lib/tour/tourAnalyticsCollector.ts","../node_modules/lodash-es/_freeGlobal.js","../node_modules/lodash-es/_root.js","../node_modules/lodash-es/_Symbol.js","../node_modules/lodash-es/_getRawTag.js","../node_modules/lodash-es/_objectToString.js","../node_modules/lodash-es/_baseGetTag.js","../node_modules/lodash-es/isObjectLike.js","../node_modules/lodash-es/isSymbol.js","../node_modules/lodash-es/_arrayMap.js","../node_modules/lodash-es/isArray.js","../node_modules/lodash-es/_baseToString.js","../node_modules/lodash-es/_trimmedEndIndex.js","../node_modules/lodash-es/_baseTrim.js","../node_modules/lodash-es/isObject.js","../node_modules/lodash-es/toNumber.js","../node_modules/lodash-es/identity.js","../node_modules/lodash-es/isFunction.js","../node_modules/lodash-es/_coreJsData.js","../node_modules/lodash-es/_isMasked.js","../node_modules/lodash-es/_toSource.js","../node_modules/lodash-es/_baseIsNative.js","../node_modules/lodash-es/_getValue.js","../node_modules/lodash-es/_getNative.js","../node_modules/lodash-es/_WeakMap.js","../node_modules/lodash-es/_baseCreate.js","../node_modules/lodash-es/_apply.js","../node_modules/lodash-es/_copyArray.js","../node_modules/lodash-es/_shortOut.js","../node_modules/lodash-es/constant.js","../node_modules/lodash-es/_defineProperty.js","../node_modules/lodash-es/_baseSetToString.js","../node_modules/lodash-es/_setToString.js","../node_modules/lodash-es/_isIndex.js","../node_modules/lodash-es/_baseAssignValue.js","../node_modules/lodash-es/eq.js","../node_modules/lodash-es/_assignValue.js","../node_modules/lodash-es/_copyObject.js","../node_modules/lodash-es/_overRest.js","../node_modules/lodash-es/_baseRest.js","../node_modules/lodash-es/isLength.js","../node_modules/lodash-es/isArrayLike.js","../node_modules/lodash-es/_isIterateeCall.js","../node_modules/lodash-es/_createAssigner.js","../node_modules/lodash-es/_isPrototype.js","../node_modules/lodash-es/_baseTimes.js","../node_modules/lodash-es/_baseIsArguments.js","../node_modules/lodash-es/isArguments.js","../node_modules/lodash-es/stubFalse.js","../node_modules/lodash-es/isBuffer.js","../node_modules/lodash-es/_baseIsTypedArray.js","../node_modules/lodash-es/_baseUnary.js","../node_modules/lodash-es/_nodeUtil.js","../node_modules/lodash-es/isTypedArray.js","../node_modules/lodash-es/_arrayLikeKeys.js","../node_modules/lodash-es/_overArg.js","../node_modules/lodash-es/_nativeKeys.js","../node_modules/lodash-es/_baseKeys.js","../node_modules/lodash-es/keys.js","../node_modules/lodash-es/_nativeKeysIn.js","../node_modules/lodash-es/_baseKeysIn.js","../node_modules/lodash-es/keysIn.js","../node_modules/lodash-es/_isKey.js","../node_modules/lodash-es/_nativeCreate.js","../node_modules/lodash-es/_hashClear.js","../node_modules/lodash-es/_hashDelete.js","../node_modules/lodash-es/_hashGet.js","../node_modules/lodash-es/_hashHas.js","../node_modules/lodash-es/_hashSet.js","../node_modules/lodash-es/_Hash.js","../node_modules/lodash-es/_listCacheClear.js","../node_modules/lodash-es/_assocIndexOf.js","../node_modules/lodash-es/_listCacheDelete.js","../node_modules/lodash-es/_listCacheGet.js","../node_modules/lodash-es/_listCacheHas.js","../node_modules/lodash-es/_listCacheSet.js","../node_modules/lodash-es/_ListCache.js","../node_modules/lodash-es/_Map.js","../node_modules/lodash-es/_mapCacheClear.js","../node_modules/lodash-es/_isKeyable.js","../node_modules/lodash-es/_getMapData.js","../node_modules/lodash-es/_mapCacheDelete.js","../node_modules/lodash-es/_mapCacheGet.js","../node_modules/lodash-es/_mapCacheHas.js","../node_modules/lodash-es/_mapCacheSet.js","../node_modules/lodash-es/_MapCache.js","../node_modules/lodash-es/memoize.js","../node_modules/lodash-es/_memoizeCapped.js","../node_modules/lodash-es/_stringToPath.js","../node_modules/lodash-es/toString.js","../node_modules/lodash-es/_castPath.js","../node_modules/lodash-es/_toKey.js","../node_modules/lodash-es/_baseGet.js","../node_modules/lodash-es/get.js","../node_modules/lodash-es/_arrayPush.js","../node_modules/lodash-es/_isFlattenable.js","../node_modules/lodash-es/_baseFlatten.js","../node_modules/lodash-es/_getPrototype.js","../node_modules/lodash-es/isPlainObject.js","../node_modules/lodash-es/_stackClear.js","../node_modules/lodash-es/_stackDelete.js","../node_modules/lodash-es/_stackGet.js","../node_modules/lodash-es/_stackHas.js","../node_modules/lodash-es/_stackSet.js","../node_modules/lodash-es/_Stack.js","../node_modules/lodash-es/_cloneBuffer.js","../node_modules/lodash-es/_arrayFilter.js","../node_modules/lodash-es/stubArray.js","../node_modules/lodash-es/_getSymbols.js","../node_modules/lodash-es/_getSymbolsIn.js","../node_modules/lodash-es/_baseGetAllKeys.js","../node_modules/lodash-es/_getAllKeys.js","../node_modules/lodash-es/_getAllKeysIn.js","../node_modules/lodash-es/_DataView.js","../node_modules/lodash-es/_Promise.js","../node_modules/lodash-es/_Set.js","../node_modules/lodash-es/_getTag.js","../node_modules/lodash-es/_Uint8Array.js","../node_modules/lodash-es/_cloneArrayBuffer.js","../node_modules/lodash-es/_cloneTypedArray.js","../node_modules/lodash-es/_initCloneObject.js","../node_modules/lodash-es/_setCacheAdd.js","../node_modules/lodash-es/_setCacheHas.js","../node_modules/lodash-es/_SetCache.js","../node_modules/lodash-es/_arraySome.js","../node_modules/lodash-es/_cacheHas.js","../node_modules/lodash-es/_equalArrays.js","../node_modules/lodash-es/_mapToArray.js","../node_modules/lodash-es/_setToArray.js","../node_modules/lodash-es/_equalByTag.js","../node_modules/lodash-es/_equalObjects.js","../node_modules/lodash-es/_baseIsEqualDeep.js","../node_modules/lodash-es/_baseIsEqual.js","../node_modules/lodash-es/_baseIsMatch.js","../node_modules/lodash-es/_isStrictComparable.js","../node_modules/lodash-es/_getMatchData.js","../node_modules/lodash-es/_matchesStrictComparable.js","../node_modules/lodash-es/_baseMatches.js","../node_modules/lodash-es/_baseHasIn.js","../node_modules/lodash-es/_hasPath.js","../node_modules/lodash-es/hasIn.js","../node_modules/lodash-es/_baseMatchesProperty.js","../node_modules/lodash-es/_baseProperty.js","../node_modules/lodash-es/_basePropertyDeep.js","../node_modules/lodash-es/property.js","../node_modules/lodash-es/_baseIteratee.js","../node_modules/lodash-es/_createBaseFor.js","../node_modules/lodash-es/_baseFor.js","../node_modules/lodash-es/_baseForOwn.js","../node_modules/lodash-es/_createBaseEach.js","../node_modules/lodash-es/_baseEach.js","../node_modules/lodash-es/now.js","../node_modules/lodash-es/debounce.js","../node_modules/lodash-es/_assignMergeValue.js","../node_modules/lodash-es/isArrayLikeObject.js","../node_modules/lodash-es/_safeGet.js","../node_modules/lodash-es/toPlainObject.js","../node_modules/lodash-es/_baseMergeDeep.js","../node_modules/lodash-es/_baseMerge.js","../node_modules/lodash-es/_baseMap.js","../node_modules/lodash-es/isEqual.js","../node_modules/lodash-es/merge.js","../node_modules/lodash-es/_baseSet.js","../node_modules/lodash-es/_basePickBy.js","../node_modules/lodash-es/pickBy.js","../node_modules/lodash-es/_baseSortBy.js","../node_modules/lodash-es/_compareAscending.js","../node_modules/lodash-es/_compareMultiple.js","../node_modules/lodash-es/_baseOrderBy.js","../node_modules/lodash-es/sortBy.js","../node_modules/lodash-es/throttle.js","../src/lib/window.ts","../node_modules/mobx-utils/mobx-utils.module.js","../node_modules/xstate/dev/dist/xstate-dev.esm.js","../node_modules/xstate/dist/State-cdbc7940.esm.js","../node_modules/xstate/dist/log-54d038f7.esm.js","../node_modules/xstate/actors/dist/xstate-actors.esm.js","../node_modules/xstate/dist/xstate.esm.js","../src/lib/tour/tourPlayback/avatarManager.fsm.ts","../node_modules/bowser/src/constants.js","../node_modules/bowser/src/utils.js","../node_modules/bowser/src/parser-browsers.js","../node_modules/bowser/src/parser-os.js","../node_modules/bowser/src/parser-platforms.js","../node_modules/bowser/src/parser-engines.js","../node_modules/bowser/src/parser.js","../node_modules/bowser/src/bowser.js","../src/lib/browser.ts","../src/lib/tour/tourPlayback/avatarManager.events.ts","../src/lib/events/eventEmitter.ts","../src/lib/tour/tourPlayback/avatarManager.ts","../src/lib/tour/tourPlayback/facades.ts","../src/lib/tour/tourPlayback/flow.ts","../../common/node_modules/uuid/dist/esm-browser/stringify.js","../../common/node_modules/uuid/dist/esm-browser/rng.js","../../common/node_modules/uuid/dist/esm-browser/native.js","../../common/node_modules/uuid/dist/esm-browser/v4.js","../../common/node_modules/zod/lib/index.mjs","../../common/dist/mjs/schemas/form/html-content.js","../../common/dist/mjs/models/v2/step.js","../src/lib/events/simpleEventEmitter.ts","../src/lib/tour/steps/v2/base.ts","../src/lib/Deferred.ts","../node_modules/lodash/isObject.js","../node_modules/lodash/_freeGlobal.js","../node_modules/lodash/_root.js","../node_modules/lodash/now.js","../node_modules/lodash/_trimmedEndIndex.js","../node_modules/lodash/_baseTrim.js","../node_modules/lodash/_Symbol.js","../node_modules/lodash/_getRawTag.js","../node_modules/lodash/_objectToString.js","../node_modules/lodash/_baseGetTag.js","../node_modules/lodash/isObjectLike.js","../node_modules/lodash/isSymbol.js","../node_modules/lodash/toNumber.js","../node_modules/lodash/debounce.js","../node_modules/lodash/throttle.js","../src/lib/element.ts","../src/lib/tour/steps/v2/modal.ts","../src/lib/tour/steps/v2/question.ts","../src/lib/storage.ts","../src/lib/tour/persistent-storage/avatarState.ts","../src/lib/tour/checkpoint.ts","../src/lib/tour/persistent-storage/tourState.ts","../../common/dist/mjs/targeting/audience-check.js","../src/stores/PageInfo.ts","../src/lib/tour/onTrackConditionCheck.ts","../src/lib/tour/tourTrackManager.events.ts","../src/lib/tour/steps/v2/waitForElement.ts","../src/lib/tour/tourTrackManager.ts","../src/lib/tour/tourPlayback/flowStateMachine.ts","../src/lib/tour/tourPlayback/tourPlaybackManager.events.ts","../src/lib/tour/steps/v2/filler.ts","../src/lib/tour/steps/v2/userClick.ts","../src/lib/tour/steps/v2/drag.ts","../src/lib/tour/steps/v2/highlight.ts","../src/lib/tour/steps/v2/showContent.ts","../src/lib/tour/steps/v2/autoType.ts","../src/lib/tour/steps/v2/autoClick.ts","../src/lib/tour/steps/v2/sleep.ts","../src/lib/tour/steps/v2/redirect.ts","../src/lib/tour/steps/v2/step.ts","../src/lib/tour/hooks/finishTour.ts","../src/lib/tour/hooks/loadCheckpoint.ts","../src/lib/tour/hooks/hook.ts","../src/lib/tour/tourPlayback/build.ts","../src/lib/tour/persistent-storage/userState.ts","../src/lib/tour/tourPlayback/tourFinishManager.events.ts","../src/lib/tour/tourPlayback/tourFinishManager.ts","../src/lib/tour/tourPlayback/tourEngagedManager.events.ts","../src/lib/tour/tourPlayback/tourEngagedManager.ts","../src/lib/tour/tourPlayback/tourPlaybackManager.ts","../src/lib/tour/tourLifecycleManager.events.ts","../src/lib/tour/tourLifecycleManager.ts","../src/PyneClient.ts","../../common/dist/mjs/targeting/ClientGuideTargetingEvaluator.js","../src/stores/SelectorObserver.ts","../src/stores/GuideTargetingEvaluator.ts","../../common/node_modules/lodash/_listCacheClear.js","../../common/node_modules/lodash/eq.js","../../common/node_modules/lodash/_assocIndexOf.js","../../common/node_modules/lodash/_listCacheDelete.js","../../common/node_modules/lodash/_listCacheGet.js","../../common/node_modules/lodash/_listCacheHas.js","../../common/node_modules/lodash/_listCacheSet.js","../../common/node_modules/lodash/_ListCache.js","../../common/node_modules/lodash/_stackClear.js","../../common/node_modules/lodash/_stackDelete.js","../../common/node_modules/lodash/_stackGet.js","../../common/node_modules/lodash/_stackHas.js","../../common/node_modules/lodash/_freeGlobal.js","../../common/node_modules/lodash/_root.js","../../common/node_modules/lodash/_Symbol.js","../../common/node_modules/lodash/_getRawTag.js","../../common/node_modules/lodash/_objectToString.js","../../common/node_modules/lodash/_baseGetTag.js","../../common/node_modules/lodash/isObject.js","../../common/node_modules/lodash/isFunction.js","../../common/node_modules/lodash/_coreJsData.js","../../common/node_modules/lodash/_isMasked.js","../../common/node_modules/lodash/_toSource.js","../../common/node_modules/lodash/_baseIsNative.js","../../common/node_modules/lodash/_getValue.js","../../common/node_modules/lodash/_getNative.js","../../common/node_modules/lodash/_Map.js","../../common/node_modules/lodash/_nativeCreate.js","../../common/node_modules/lodash/_hashClear.js","../../common/node_modules/lodash/_hashDelete.js","../../common/node_modules/lodash/_hashGet.js","../../common/node_modules/lodash/_hashHas.js","../../common/node_modules/lodash/_hashSet.js","../../common/node_modules/lodash/_Hash.js","../../common/node_modules/lodash/_mapCacheClear.js","../../common/node_modules/lodash/_isKeyable.js","../../common/node_modules/lodash/_getMapData.js","../../common/node_modules/lodash/_mapCacheDelete.js","../../common/node_modules/lodash/_mapCacheGet.js","../../common/node_modules/lodash/_mapCacheHas.js","../../common/node_modules/lodash/_mapCacheSet.js","../../common/node_modules/lodash/_MapCache.js","../../common/node_modules/lodash/_stackSet.js","../../common/node_modules/lodash/_Stack.js","../../common/node_modules/lodash/_defineProperty.js","../../common/node_modules/lodash/_baseAssignValue.js","../../common/node_modules/lodash/_assignMergeValue.js","../../common/node_modules/lodash/_createBaseFor.js","../../common/node_modules/lodash/_baseFor.js","../../common/node_modules/lodash/_cloneBuffer.js","../../common/node_modules/lodash/_Uint8Array.js","../../common/node_modules/lodash/_cloneArrayBuffer.js","../../common/node_modules/lodash/_cloneTypedArray.js","../../common/node_modules/lodash/_copyArray.js","../../common/node_modules/lodash/_baseCreate.js","../../common/node_modules/lodash/_overArg.js","../../common/node_modules/lodash/_getPrototype.js","../../common/node_modules/lodash/_isPrototype.js","../../common/node_modules/lodash/_initCloneObject.js","../../common/node_modules/lodash/isObjectLike.js","../../common/node_modules/lodash/_baseIsArguments.js","../../common/node_modules/lodash/isArguments.js","../../common/node_modules/lodash/isArray.js","../../common/node_modules/lodash/isLength.js","../../common/node_modules/lodash/isArrayLike.js","../../common/node_modules/lodash/isArrayLikeObject.js","../../common/node_modules/lodash/stubFalse.js","../../common/node_modules/lodash/isBuffer.js","../../common/node_modules/lodash/isPlainObject.js","../../common/node_modules/lodash/_baseIsTypedArray.js","../../common/node_modules/lodash/_baseUnary.js","../../common/node_modules/lodash/_nodeUtil.js","../../common/node_modules/lodash/isTypedArray.js","../../common/node_modules/lodash/_safeGet.js","../../common/node_modules/lodash/_assignValue.js","../../common/node_modules/lodash/_copyObject.js","../../common/node_modules/lodash/_baseTimes.js","../../common/node_modules/lodash/_isIndex.js","../../common/node_modules/lodash/_arrayLikeKeys.js","../../common/node_modules/lodash/_nativeKeysIn.js","../../common/node_modules/lodash/_baseKeysIn.js","../../common/node_modules/lodash/keysIn.js","../../common/node_modules/lodash/toPlainObject.js","../../common/node_modules/lodash/_baseMergeDeep.js","../../common/node_modules/lodash/_baseMerge.js","../../common/node_modules/lodash/identity.js","../../common/node_modules/lodash/_apply.js","../../common/node_modules/lodash/_overRest.js","../../common/node_modules/lodash/constant.js","../../common/node_modules/lodash/_baseSetToString.js","../../common/node_modules/lodash/_shortOut.js","../../common/node_modules/lodash/_setToString.js","../../common/node_modules/lodash/_baseRest.js","../../common/node_modules/lodash/_isIterateeCall.js","../../common/node_modules/lodash/_createAssigner.js","../../common/node_modules/lodash/merge.js","../../common/dist/mjs/models/guide.js","../src/lib/tour/guideScheduler.events.ts","../src/lib/tour/guideScheduler.ts","../src/lib/tour/persistent-storage/tabState.ts","../src/lib/tour/persistent-storage/previewState.ts","../src/lib/tour/persistent-storage/sessionState.ts","../src/lib/tour/persistent-storage/debuggerState.ts","../src/lib/tour/persistent-storage/storage.ts","../src/stores/AvatarPositioner.ts","../src/lib/tour/tourStartManager.ts","../src/lib/tour/tabManager.events.ts","../src/lib/tour/tabManager.ts","../src/stores/DebuggerManager.ts","../src/stores/PromptPositioner.ts","../src/stores/GuideRegistry.ts","../src/AssetManager.ts","../src/lib/tour/tourSessionManager.events.ts","../src/lib/tour/tourSessionManager.ts","../src/stores/PreviewManager.ts","../src/store.ts","../node_modules/lucide-react/dist/esm/defaultAttributes.js","../node_modules/lucide-react/dist/esm/shared/src/utils.js","../node_modules/lucide-react/dist/esm/createLucideIcon.js","../node_modules/lucide-react/dist/esm/icons/box.js","../node_modules/lucide-react/dist/esm/icons/captions-off.js","../node_modules/lucide-react/dist/esm/icons/captions.js","../node_modules/lucide-react/dist/esm/icons/check.js","../node_modules/lucide-react/dist/esm/icons/chevron-down.js","../node_modules/lucide-react/dist/esm/icons/chevron-left.js","../node_modules/lucide-react/dist/esm/icons/chevron-up.js","../node_modules/lucide-react/dist/esm/icons/circle-check.js","../node_modules/lucide-react/dist/esm/icons/circle-help.js","../node_modules/lucide-react/dist/esm/icons/copy.js","../node_modules/lucide-react/dist/esm/icons/ellipsis.js","../node_modules/lucide-react/dist/esm/icons/expand.js","../node_modules/lucide-react/dist/esm/icons/land-plot.js","../node_modules/lucide-react/dist/esm/icons/loader-circle.js","../node_modules/lucide-react/dist/esm/icons/minimize-2.js","../node_modules/lucide-react/dist/esm/icons/minimize.js","../node_modules/lucide-react/dist/esm/icons/pause.js","../node_modules/lucide-react/dist/esm/icons/play.js","../node_modules/lucide-react/dist/esm/icons/rotate-ccw.js","../node_modules/lucide-react/dist/esm/icons/scroll-text.js","../node_modules/lucide-react/dist/esm/icons/skip-forward.js","../node_modules/lucide-react/dist/esm/icons/trash.js","../node_modules/lucide-react/dist/esm/icons/user.js","../node_modules/lucide-react/dist/esm/icons/volume-1.js","../node_modules/lucide-react/dist/esm/icons/volume-x.js","../node_modules/lucide-react/dist/esm/icons/x.js","../node_modules/lodash.debounce/index.js","../node_modules/usehooks-ts/dist/index.mjs","../node_modules/@floating-ui/utils/dom/dist/floating-ui.utils.dom.mjs","../node_modules/@floating-ui/react/utils/dist/floating-ui.react.utils.mjs","../node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs","../node_modules/@floating-ui/core/dist/floating-ui.core.mjs","../node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs","../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.mjs","../node_modules/tabbable/dist/index.esm.js","../node_modules/@floating-ui/react/dist/floating-ui.react.mjs","../src/components/AvatarTooltip.tsx","../src/components/AvatarButton.tsx","../src/components/AvatarDragOverlay.tsx","../src/components/element-higlighter/FloatingDot.tsx","../src/components/element-higlighter/ElementPointer.tsx","../src/components/VirtualCursorSvg.tsx","../src/components/ShadowDomContainer.tsx","../src/components/VirtualCursor.tsx","../src/assets/logo-without-brand.svg","../src/components/Avatar.tsx","../src/components/element-higlighter/PulsatingBorderHighlight.tsx","../src/components/element-higlighter/BackdropHighlight.tsx","../src/components/element-higlighter/ElementHiglighterV2.tsx","../src/components/MinimizedAvatar.tsx","../src/components/ProgressRing.tsx","../src/components/dynamic-content/allowlist.ts","../src/components/dynamic-content/createSafeContentNode.ts","../src/components/dynamic-content/parseHtml.ts","../src/components/dynamic-content/DynamicContent.tsx","../src/components/Tooltip.tsx","../src/components/Logo.tsx","../src/components/PromptCard.tsx","../src/components/Dialog.tsx","../src/components/TheyDoModal.tsx","../src/components/intro/Dialog.tsx","../src/components/tour/steps/TourModalV2.tsx","../src/components/intro/Popover.tsx","../src/components/intro/Intro.tsx","../src/components/AvatarSkeleton.tsx","../src/components/tour/tour-player/TourPlayer.tsx","../src/components/preview/PreviewMode.tsx","../src/lib/cssAnimation.ts","../src/components/debugger/GuideListModal.tsx","../src/components/Switch.tsx","../src/components/debugger/PlayCircle.tsx","../src/components/debugger/TourPlaybackVisualizer.tsx","../src/components/debugger/CheckIcon.tsx","../src/components/debugger/CrossIcon.tsx","../src/components/debugger/TourDetailsModal.tsx","../src/components/debugger/UserDataModal.tsx","../src/components/debugger/StateDataModal.tsx","../src/components/debugger/Debugger.v2.tsx","../src/App.tsx","../src/lib/disableGlobalFocusTrapForPyneUI.tsx","../src/installSegmentIntegration.ts","../src/loadCustomPyneSettings.ts","../src/index.ts"],"sourcesContent":["/**\n * @license React\n * react.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var l=Symbol.for(\"react.element\"),n=Symbol.for(\"react.portal\"),p=Symbol.for(\"react.fragment\"),q=Symbol.for(\"react.strict_mode\"),r=Symbol.for(\"react.profiler\"),t=Symbol.for(\"react.provider\"),u=Symbol.for(\"react.context\"),v=Symbol.for(\"react.forward_ref\"),w=Symbol.for(\"react.suspense\"),x=Symbol.for(\"react.memo\"),y=Symbol.for(\"react.lazy\"),z=Symbol.iterator;function A(a){if(null===a||\"object\"!==typeof a)return null;a=z&&a[z]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}\nvar B={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}E.prototype.isReactComponent={};\nE.prototype.setState=function(a,b){if(\"object\"!==typeof a&&\"function\"!==typeof a&&null!=a)throw Error(\"setState(...): takes an object of state variables to update or a function which returns an object of state variables.\");this.updater.enqueueSetState(this,a,b,\"setState\")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,\"forceUpdate\")};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}var H=G.prototype=new F;\nH.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0};\nfunction M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=\"\"+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","/**\n * @license React\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;cb}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(ra,\nsa);z[b]=new v(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"\")&&(k=k.replace(\"\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e\"+b.valueOf().toString()+\"\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&uh(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=sh(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Ah(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=yh(f.type,f.key,f.props,null,a.mode,h),h.ref=sh(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==\nd;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=zh(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);th(a,f)}return\"string\"===typeof f&&\"\"!==f||\"number\"===typeof f?(f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):\n(c(a,d),d=xh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Bh=vh(!0),Ch=vh(!1),Dh={},Eh=Uf(Dh),Fh=Uf(Dh),Gh=Uf(Dh);function Hh(a){if(a===Dh)throw Error(p(174));return a}function Ih(a,b){G(Gh,b);G(Fh,a);G(Eh,Dh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,\"\");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a)}E(Eh);G(Eh,b)}function Jh(){E(Eh);E(Fh);E(Gh)}\nfunction Kh(a){Hh(Gh.current);var b=Hh(Eh.current);var c=lb(b,a.type);b!==c&&(G(Fh,a),G(Eh,c))}function Lh(a){Fh.current===a&&(E(Eh),E(Fh))}var M=Uf(0);\nfunction Mh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||\"$?\"===c.data||\"$!\"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}var Nh=[];\nfunction Oh(){for(var a=0;ac?c:4;a(!0);var d=Qh.transition;Qh.transition={};try{a(!1),b()}finally{C=c,Qh.transition=d}}function Fi(){return di().memoizedState}\nfunction Gi(a,b,c){var d=lh(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,c);else if(c=Yg(a,b,c,d),null!==c){var e=L();mh(c,a,d,e);Ji(c,b,d)}}\nfunction ri(a,b,c){var d=lh(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,Xg(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=Yg(a,b,e,d);null!==c&&(e=L(),mh(c,a,d,e),Ji(c,b,d))}}\nfunction Hi(a){var b=a.alternate;return a===N||null!==b&&b===N}function Ii(a,b){Th=Sh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Ji(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nvar ai={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},Yh={readContext:Vg,useCallback:function(a,b){ci().memoizedState=[a,void 0===b?null:b];return a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ti(4194308,\n4,yi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ti(4194308,4,a,b)},useInsertionEffect:function(a,b){return ti(4,2,a,b)},useMemo:function(a,b){var c=ci();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=ci();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Gi.bind(null,N,a);return[d.memoizedState,a]},useRef:function(a){var b=\nci();a={current:a};return b.memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),b=a[0];a=Ei.bind(null,a[1]);ci().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=N,e=ci();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===R)throw Error(p(349));0!==(Rh&30)||ni(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;vi(ki.bind(null,d,\nf,a),[a]);d.flags|=2048;li(9,mi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=ci(),b=R.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=\":\"+b+\"R\"+c;c=Uh++;0\\x3c/script>\",a=a.removeChild(a.firstChild)):\n\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;Aj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case \"dialog\":D(\"cancel\",a);D(\"close\",a);e=d;break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;eHj&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304)}else{if(!d)if(a=Mh(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Ej(f,!0),null===f.tail&&\"hidden\"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Hj&&1073741824!==c&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=\nb,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=M.current,G(M,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Ij(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(gj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}\nfunction Jj(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Jh(),E(Wf),E(H),Oh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Lh(b),null;case 13:E(M);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(M),null;case 4:return Jh(),null;case 10:return Rg(b.type._context),null;case 22:case 23:return Ij(),\nnull;case 24:return null;default:return null}}var Kj=!1,U=!1,Lj=\"function\"===typeof WeakSet?WeakSet:Set,V=null;function Mj(a,b){var c=a.ref;if(null!==c)if(\"function\"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Nj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Oj=!1;\nfunction Pj(a,b){Cf=dd;a=Me();if(Ne(a)){if(\"selectionStart\"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=\nq.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;\ncase 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Lg(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent=\"\":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Oj;Oj=!1;return n}\nfunction Qj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Nj(b,c,f)}e=e.next}while(e!==d)}}function Rj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Sj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}\"function\"===typeof b?b(a):b.current=a}}\nfunction Tj(a){var b=a.alternate;null!==b&&(a.alternate=null,Tj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction Vj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}\nfunction Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}\nfunction Xj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Xj(a,b,c),a=a.sibling;null!==a;)Xj(a,b,c),a=a.sibling}var X=null,Yj=!1;function Zj(a,b,c){for(c=c.child;null!==c;)ak(a,b,c),c=c.sibling}\nfunction ak(a,b,c){if(lc&&\"function\"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Mj(c,b);case 6:var d=X,e=Yj;X=null;Zj(a,b,c);X=d;Yj=e;null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Yj;X=c.stateNode.containerInfo;Yj=!0;\nZj(a,b,c);X=d;Yj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Nj(c,b,g):0!==(f&4)&&Nj(c,b,g));e=e.next}while(e!==d)}Zj(a,b,c);break;case 1:if(!U&&(Mj(c,b),d=c.stateNode,\"function\"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Zj(a,b,c);break;case 21:Zj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==\nc.memoizedState,Zj(a,b,c),U=d):Zj(a,b,c);break;default:Zj(a,b,c)}}function bk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Lj);b.forEach(function(b){var d=ck.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction dk(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*mk(d/1960))-d;if(10a?16:a;if(null===xk)var d=!1;else{a=xk;xk=null;yk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-gk?Lk(a,0):sk|=c);Ek(a,b)}function Zk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=L();a=Zg(a,b);null!==a&&(Ac(a,b,c),Ek(a,c))}function vj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Zk(a,c)}\nfunction ck(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Zk(a,c)}var Wk;\nWk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)Ug=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return Ug=!1,zj(a,b,c);Ug=0!==(a.flags&131072)?!0:!1}else Ug=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;jj(a,b);a=b.pendingProps;var e=Yf(b,H.current);Tg(b,c);e=Xh(null,b,d,a,e,c);var f=bi();b.flags|=1;\"object\"===typeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=\nnull,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ah(b),e.updater=nh,b.stateNode=e,e._reactInternals=b,rh(b,d,a,c),b=kj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Yi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{jj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=$k(d);a=Lg(d,a);switch(e){case 0:b=dj(null,b,d,a,c);break a;case 1:b=ij(null,b,d,a,c);break a;case 11:b=Zi(null,b,d,a,c);break a;case 14:b=aj(null,b,d,Lg(d.type,a),c);break a}throw Error(p(306,\nd,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),dj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),ij(a,b,d,e,c);case 3:a:{lj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;bh(a,b);gh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=\nf,b.memoizedState=f,b.flags&256){e=Ki(Error(p(423)),b);b=mj(a,b,d,c,e);break a}else if(d!==e){e=Ki(Error(p(424)),b);b=mj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Ch(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=$i(a,b,c);break a}Yi(a,b,d,c)}b=b.child}return b;case 5:return Kh(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),\nhj(a,b),Yi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return pj(a,b,c);case 4:return Ih(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Bh(b,null,d,c):Yi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),Zi(a,b,d,e,c);case 7:return Yi(a,b,b.pendingProps,c),b.child;case 8:return Yi(a,b,b.pendingProps.children,c),b.child;case 12:return Yi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;\ng=e.value;G(Mg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=$i(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ch(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);Sg(f.return,\nc,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);Sg(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Yi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,Tg(b,c),e=Vg(e),d=d(e),b.flags|=1,Yi(a,b,d,c),\nb.child;case 14:return d=b.type,e=Lg(d,b.pendingProps),e=Lg(d.type,e),aj(a,b,d,e,c);case 15:return cj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),jj(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,Tg(b,c),ph(b,d,e),rh(b,d,e,c),kj(null,b,d,!0,a,c);case 19:return yj(a,b,c);case 22:return ej(a,b,c)}throw Error(p(156,b.tag));};function Gk(a,b){return ac(a,b)}\nfunction al(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new al(a,b,c,d)}function bj(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction $k(a){if(\"function\"===typeof a)return bj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}\nfunction wh(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};\nc.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}\nfunction yh(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)bj(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ya:return Ah(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return qj(c,e,f,b);default:if(\"object\"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;\nbreak a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,\"\"));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Ah(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function qj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function xh(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}\nfunction zh(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}\nfunction bl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=\nnull}function cl(a,b,c,d,e,f,g,h,k){a=new bl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};ah(f);return a}function dl(a,b,c){var d=3 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n if (process.env.NODE_ENV !== \"production\") {\n var e = typeof error === \"string\" ? error : errors[error];\n if (typeof e === \"function\") e = e.apply(null, args);\n throw new Error(\"[MobX] \" + e);\n }\n throw new Error(typeof error === \"number\" ? \"[MobX] minified error nr: \" + error + (args.length ? \" \" + args.map(String).join(\",\") : \"\") + \". Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts\" : \"[MobX] \" + error);\n}\n\nvar mockGlobal = {};\nfunction getGlobal() {\n if (typeof globalThis !== \"undefined\") {\n return globalThis;\n }\n if (typeof window !== \"undefined\") {\n return window;\n }\n if (typeof global !== \"undefined\") {\n return global;\n }\n if (typeof self !== \"undefined\") {\n return self;\n }\n return mockGlobal;\n}\n\n// We shorten anything used > 5 times\nvar assign = Object.assign;\nvar getDescriptor = Object.getOwnPropertyDescriptor;\nvar defineProperty = Object.defineProperty;\nvar objectPrototype = Object.prototype;\nvar EMPTY_ARRAY = [];\nObject.freeze(EMPTY_ARRAY);\nvar EMPTY_OBJECT = {};\nObject.freeze(EMPTY_OBJECT);\nvar hasProxy = typeof Proxy !== \"undefined\";\nvar plainObjectString = /*#__PURE__*/Object.toString();\nfunction assertProxies() {\n if (!hasProxy) {\n die(process.env.NODE_ENV !== \"production\" ? \"`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`\" : \"Proxy not available\");\n }\n}\nfunction warnAboutProxyRequirement(msg) {\n if (process.env.NODE_ENV !== \"production\" && globalState.verifyProxies) {\n die(\"MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to \" + msg);\n }\n}\nfunction getNextId() {\n return ++globalState.mobxGuid;\n}\n/**\n * Makes sure that the provided function is invoked at most once.\n */\nfunction once(func) {\n var invoked = false;\n return function () {\n if (invoked) {\n return;\n }\n invoked = true;\n return func.apply(this, arguments);\n };\n}\nvar noop = function noop() {};\nfunction isFunction(fn) {\n return typeof fn === \"function\";\n}\nfunction isStringish(value) {\n var t = typeof value;\n switch (t) {\n case \"string\":\n case \"symbol\":\n case \"number\":\n return true;\n }\n return false;\n}\nfunction isObject(value) {\n return value !== null && typeof value === \"object\";\n}\nfunction isPlainObject(value) {\n if (!isObject(value)) {\n return false;\n }\n var proto = Object.getPrototypeOf(value);\n if (proto == null) {\n return true;\n }\n var protoConstructor = Object.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof protoConstructor === \"function\" && protoConstructor.toString() === plainObjectString;\n}\n// https://stackoverflow.com/a/37865170\nfunction isGenerator(obj) {\n var constructor = obj == null ? void 0 : obj.constructor;\n if (!constructor) {\n return false;\n }\n if (\"GeneratorFunction\" === constructor.name || \"GeneratorFunction\" === constructor.displayName) {\n return true;\n }\n return false;\n}\nfunction addHiddenProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: true,\n configurable: true,\n value: value\n });\n}\nfunction addHiddenFinalProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: false,\n configurable: true,\n value: value\n });\n}\nfunction createInstanceofPredicate(name, theClass) {\n var propName = \"isMobX\" + name;\n theClass.prototype[propName] = true;\n return function (x) {\n return isObject(x) && x[propName] === true;\n };\n}\nfunction isES6Map(thing) {\n return thing instanceof Map;\n}\nfunction isES6Set(thing) {\n return thing instanceof Set;\n}\nvar hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== \"undefined\";\n/**\n * Returns the following: own enumerable keys and symbols.\n */\nfunction getPlainObjectKeys(object) {\n var keys = Object.keys(object);\n // Not supported in IE, so there are not going to be symbol props anyway...\n if (!hasGetOwnPropertySymbols) {\n return keys;\n }\n var symbols = Object.getOwnPropertySymbols(object);\n if (!symbols.length) {\n return keys;\n }\n return [].concat(keys, symbols.filter(function (s) {\n return objectPrototype.propertyIsEnumerable.call(object, s);\n }));\n}\n// From Immer utils\n// Returns all own keys, including non-enumerable and symbolic\nvar ownKeys = typeof Reflect !== \"undefined\" && Reflect.ownKeys ? Reflect.ownKeys : hasGetOwnPropertySymbols ? function (obj) {\n return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));\n} : /* istanbul ignore next */Object.getOwnPropertyNames;\nfunction stringifyKey(key) {\n if (typeof key === \"string\") {\n return key;\n }\n if (typeof key === \"symbol\") {\n return key.toString();\n }\n return new String(key).toString();\n}\nfunction toPrimitive(value) {\n return value === null ? null : typeof value === \"object\" ? \"\" + value : value;\n}\nfunction hasProp(target, prop) {\n return objectPrototype.hasOwnProperty.call(target, prop);\n}\n// From Immer utils\nvar getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) {\n // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274\n var res = {};\n // Note: without polyfill for ownKeys, symbols won't be picked up\n ownKeys(target).forEach(function (key) {\n res[key] = getDescriptor(target, key);\n });\n return res;\n};\n\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}\nfunction _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}\nfunction _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}\nfunction _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n _setPrototypeOf(subClass, superClass);\n}\nfunction _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}\nfunction _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return self;\n}\nfunction _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}\nfunction _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}\nfunction _createForOfIteratorHelperLoose(o, allowArrayLike) {\n var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"];\n if (it) return (it = it.call(o)).next.bind(it);\n if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") {\n if (it) o = it;\n var i = 0;\n return function () {\n if (i >= o.length) return {\n done: true\n };\n return {\n done: false,\n value: o[i++]\n };\n };\n }\n throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nfunction _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}\nfunction _toPropertyKey(arg) {\n var key = _toPrimitive(arg, \"string\");\n return typeof key === \"symbol\" ? key : String(key);\n}\n\nvar storedAnnotationsSymbol = /*#__PURE__*/Symbol(\"mobx-stored-annotations\");\n/**\n * Creates a function that acts as\n * - decorator\n * - annotation object\n */\nfunction createDecoratorAnnotation(annotation) {\n function decorator(target, property) {\n if (is20223Decorator(property)) {\n return annotation.decorate_20223_(target, property);\n } else {\n storeAnnotation(target, property, annotation);\n }\n }\n return Object.assign(decorator, annotation);\n}\n/**\n * Stores annotation to prototype,\n * so it can be inspected later by `makeObservable` called from constructor\n */\nfunction storeAnnotation(prototype, key, annotation) {\n if (!hasProp(prototype, storedAnnotationsSymbol)) {\n addHiddenProp(prototype, storedAnnotationsSymbol, _extends({}, prototype[storedAnnotationsSymbol]));\n }\n // @override must override something\n if (process.env.NODE_ENV !== \"production\" && isOverride(annotation) && !hasProp(prototype[storedAnnotationsSymbol], key)) {\n var fieldName = prototype.constructor.name + \".prototype.\" + key.toString();\n die(\"'\" + fieldName + \"' is decorated with 'override', \" + \"but no such decorated member was found on prototype.\");\n }\n // Cannot re-decorate\n assertNotDecorated(prototype, annotation, key);\n // Ignore override\n if (!isOverride(annotation)) {\n prototype[storedAnnotationsSymbol][key] = annotation;\n }\n}\nfunction assertNotDecorated(prototype, annotation, key) {\n if (process.env.NODE_ENV !== \"production\" && !isOverride(annotation) && hasProp(prototype[storedAnnotationsSymbol], key)) {\n var fieldName = prototype.constructor.name + \".prototype.\" + key.toString();\n var currentAnnotationType = prototype[storedAnnotationsSymbol][key].annotationType_;\n var requestedAnnotationType = annotation.annotationType_;\n die(\"Cannot apply '@\" + requestedAnnotationType + \"' to '\" + fieldName + \"':\" + (\"\\nThe field is already decorated with '@\" + currentAnnotationType + \"'.\") + \"\\nRe-decorating fields is not allowed.\" + \"\\nUse '@override' decorator for methods overridden by subclass.\");\n }\n}\n/**\n * Collects annotations from prototypes and stores them on target (instance)\n */\nfunction collectStoredAnnotations(target) {\n if (!hasProp(target, storedAnnotationsSymbol)) {\n // if (__DEV__ && !target[storedAnnotationsSymbol]) {\n // die(\n // `No annotations were passed to makeObservable, but no decorated members have been found either`\n // )\n // }\n // We need a copy as we will remove annotation from the list once it's applied.\n addHiddenProp(target, storedAnnotationsSymbol, _extends({}, target[storedAnnotationsSymbol]));\n }\n return target[storedAnnotationsSymbol];\n}\nfunction is20223Decorator(context) {\n return typeof context == \"object\" && typeof context[\"kind\"] == \"string\";\n}\nfunction assert20223DecoratorType(context, types) {\n if (process.env.NODE_ENV !== \"production\" && !types.includes(context.kind)) {\n die(\"The decorator applied to '\" + String(context.name) + \"' cannot be used on a \" + context.kind + \" element\");\n }\n}\n\nvar $mobx = /*#__PURE__*/Symbol(\"mobx administration\");\nvar Atom = /*#__PURE__*/function () {\n // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed\n\n /**\n * Create a new atom. For debugging purposes it is recommended to give it a name.\n * The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management.\n */\n function Atom(name_) {\n if (name_ === void 0) {\n name_ = process.env.NODE_ENV !== \"production\" ? \"Atom@\" + getNextId() : \"Atom\";\n }\n this.name_ = void 0;\n this.isPendingUnobservation_ = false;\n this.isBeingObserved_ = false;\n this.observers_ = new Set();\n this.diffValue_ = 0;\n this.lastAccessedBy_ = 0;\n this.lowestObserverState_ = IDerivationState_.NOT_TRACKING_;\n this.onBOL = void 0;\n this.onBUOL = void 0;\n this.name_ = name_;\n }\n // onBecomeObservedListeners\n var _proto = Atom.prototype;\n _proto.onBO = function onBO() {\n if (this.onBOL) {\n this.onBOL.forEach(function (listener) {\n return listener();\n });\n }\n };\n _proto.onBUO = function onBUO() {\n if (this.onBUOL) {\n this.onBUOL.forEach(function (listener) {\n return listener();\n });\n }\n }\n /**\n * Invoke this method to notify mobx that your atom has been used somehow.\n * Returns true if there is currently a reactive context.\n */;\n _proto.reportObserved = function reportObserved$1() {\n return reportObserved(this);\n }\n /**\n * Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate.\n */;\n _proto.reportChanged = function reportChanged() {\n startBatch();\n propagateChanged(this);\n endBatch();\n };\n _proto.toString = function toString() {\n return this.name_;\n };\n return Atom;\n}();\nvar isAtom = /*#__PURE__*/createInstanceofPredicate(\"Atom\", Atom);\nfunction createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) {\n if (onBecomeObservedHandler === void 0) {\n onBecomeObservedHandler = noop;\n }\n if (onBecomeUnobservedHandler === void 0) {\n onBecomeUnobservedHandler = noop;\n }\n var atom = new Atom(name);\n // default `noop` listener will not initialize the hook Set\n if (onBecomeObservedHandler !== noop) {\n onBecomeObserved(atom, onBecomeObservedHandler);\n }\n if (onBecomeUnobservedHandler !== noop) {\n onBecomeUnobserved(atom, onBecomeUnobservedHandler);\n }\n return atom;\n}\n\nfunction identityComparer(a, b) {\n return a === b;\n}\nfunction structuralComparer(a, b) {\n return deepEqual(a, b);\n}\nfunction shallowComparer(a, b) {\n return deepEqual(a, b, 1);\n}\nfunction defaultComparer(a, b) {\n if (Object.is) {\n return Object.is(a, b);\n }\n return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;\n}\nvar comparer = {\n identity: identityComparer,\n structural: structuralComparer,\n \"default\": defaultComparer,\n shallow: shallowComparer\n};\n\nfunction deepEnhancer(v, _, name) {\n // it is an observable already, done\n if (isObservable(v)) {\n return v;\n }\n // something that can be converted and mutated?\n if (Array.isArray(v)) {\n return observable.array(v, {\n name: name\n });\n }\n if (isPlainObject(v)) {\n return observable.object(v, undefined, {\n name: name\n });\n }\n if (isES6Map(v)) {\n return observable.map(v, {\n name: name\n });\n }\n if (isES6Set(v)) {\n return observable.set(v, {\n name: name\n });\n }\n if (typeof v === \"function\" && !isAction(v) && !isFlow(v)) {\n if (isGenerator(v)) {\n return flow(v);\n } else {\n return autoAction(name, v);\n }\n }\n return v;\n}\nfunction shallowEnhancer(v, _, name) {\n if (v === undefined || v === null) {\n return v;\n }\n if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) {\n return v;\n }\n if (Array.isArray(v)) {\n return observable.array(v, {\n name: name,\n deep: false\n });\n }\n if (isPlainObject(v)) {\n return observable.object(v, undefined, {\n name: name,\n deep: false\n });\n }\n if (isES6Map(v)) {\n return observable.map(v, {\n name: name,\n deep: false\n });\n }\n if (isES6Set(v)) {\n return observable.set(v, {\n name: name,\n deep: false\n });\n }\n if (process.env.NODE_ENV !== \"production\") {\n die(\"The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets\");\n }\n}\nfunction referenceEnhancer(newValue) {\n // never turn into an observable\n return newValue;\n}\nfunction refStructEnhancer(v, oldValue) {\n if (process.env.NODE_ENV !== \"production\" && isObservable(v)) {\n die(\"observable.struct should not be used with observable values\");\n }\n if (deepEqual(v, oldValue)) {\n return oldValue;\n }\n return v;\n}\n\nvar OVERRIDE = \"override\";\nvar override = /*#__PURE__*/createDecoratorAnnotation({\n annotationType_: OVERRIDE,\n make_: make_,\n extend_: extend_,\n decorate_20223_: decorate_20223_\n});\nfunction isOverride(annotation) {\n return annotation.annotationType_ === OVERRIDE;\n}\nfunction make_(adm, key) {\n // Must not be plain object\n if (process.env.NODE_ENV !== \"production\" && adm.isPlainObject_) {\n die(\"Cannot apply '\" + this.annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + this.annotationType_ + \"' cannot be used on plain objects.\"));\n }\n // Must override something\n if (process.env.NODE_ENV !== \"production\" && !hasProp(adm.appliedAnnotations_, key)) {\n die(\"'\" + adm.name_ + \".\" + key.toString() + \"' is annotated with '\" + this.annotationType_ + \"', \" + \"but no such annotated member was found on prototype.\");\n }\n return 0 /* MakeResult.Cancel */;\n}\n\nfunction extend_(adm, key, descriptor, proxyTrap) {\n die(\"'\" + this.annotationType_ + \"' can only be used with 'makeObservable'\");\n}\nfunction decorate_20223_(desc, context) {\n console.warn(\"'\" + this.annotationType_ + \"' cannot be used with decorators - this is a no-op\");\n}\n\nfunction createActionAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$1,\n extend_: extend_$1,\n decorate_20223_: decorate_20223_$1\n };\n}\nfunction make_$1(adm, key, descriptor, source) {\n var _this$options_;\n // bound\n if ((_this$options_ = this.options_) != null && _this$options_.bound) {\n return this.extend_(adm, key, descriptor, false) === null ? 0 /* MakeResult.Cancel */ : 1 /* MakeResult.Break */;\n }\n // own\n if (source === adm.target_) {\n return this.extend_(adm, key, descriptor, false) === null ? 0 /* MakeResult.Cancel */ : 2 /* MakeResult.Continue */;\n }\n // prototype\n if (isAction(descriptor.value)) {\n // A prototype could have been annotated already by other constructor,\n // rest of the proto chain must be annotated already\n return 1 /* MakeResult.Break */;\n }\n\n var actionDescriptor = createActionDescriptor(adm, this, key, descriptor, false);\n defineProperty(source, key, actionDescriptor);\n return 2 /* MakeResult.Continue */;\n}\n\nfunction extend_$1(adm, key, descriptor, proxyTrap) {\n var actionDescriptor = createActionDescriptor(adm, this, key, descriptor);\n return adm.defineProperty_(key, actionDescriptor, proxyTrap);\n}\nfunction decorate_20223_$1(mthd, context) {\n if (process.env.NODE_ENV !== \"production\") {\n assert20223DecoratorType(context, [\"method\", \"field\"]);\n }\n var kind = context.kind,\n name = context.name,\n addInitializer = context.addInitializer;\n var ann = this;\n var _createAction = function _createAction(m) {\n var _ann$options_$name, _ann$options_, _ann$options_$autoAct, _ann$options_2;\n return createAction((_ann$options_$name = (_ann$options_ = ann.options_) == null ? void 0 : _ann$options_.name) != null ? _ann$options_$name : name.toString(), m, (_ann$options_$autoAct = (_ann$options_2 = ann.options_) == null ? void 0 : _ann$options_2.autoAction) != null ? _ann$options_$autoAct : false);\n };\n // Backwards/Legacy behavior, expects makeObservable(this)\n if (kind == \"field\") {\n addInitializer(function () {\n storeAnnotation(this, name, ann);\n });\n return;\n }\n if (kind == \"method\") {\n var _this$options_2;\n if (!isAction(mthd)) {\n mthd = _createAction(mthd);\n }\n if ((_this$options_2 = this.options_) != null && _this$options_2.bound) {\n addInitializer(function () {\n var self = this;\n var bound = self[name].bind(self);\n bound.isMobxAction = true;\n self[name] = bound;\n });\n }\n return mthd;\n }\n die(\"Cannot apply '\" + ann.annotationType_ + \"' to '\" + String(name) + \"' (kind: \" + kind + \"):\" + (\"\\n'\" + ann.annotationType_ + \"' can only be used on properties with a function value.\"));\n}\nfunction assertActionDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var value = _ref2.value;\n if (process.env.NODE_ENV !== \"production\" && !isFunction(value)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on properties with a function value.\"));\n }\n}\nfunction createActionDescriptor(adm, annotation, key, descriptor,\n// provides ability to disable safeDescriptors for prototypes\nsafeDescriptors) {\n var _annotation$options_, _annotation$options_$, _annotation$options_2, _annotation$options_$2, _annotation$options_3, _annotation$options_4, _adm$proxy_2;\n if (safeDescriptors === void 0) {\n safeDescriptors = globalState.safeDescriptors;\n }\n assertActionDescriptor(adm, annotation, key, descriptor);\n var value = descriptor.value;\n if ((_annotation$options_ = annotation.options_) != null && _annotation$options_.bound) {\n var _adm$proxy_;\n value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n }\n return {\n value: createAction((_annotation$options_$ = (_annotation$options_2 = annotation.options_) == null ? void 0 : _annotation$options_2.name) != null ? _annotation$options_$ : key.toString(), value, (_annotation$options_$2 = (_annotation$options_3 = annotation.options_) == null ? void 0 : _annotation$options_3.autoAction) != null ? _annotation$options_$2 : false,\n // https://github.com/mobxjs/mobx/discussions/3140\n (_annotation$options_4 = annotation.options_) != null && _annotation$options_4.bound ? (_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_ : undefined),\n // Non-configurable for classes\n // prevents accidental field redefinition in subclass\n configurable: safeDescriptors ? adm.isPlainObject_ : true,\n // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058\n enumerable: false,\n // Non-obsevable, therefore non-writable\n // Also prevents rewriting in subclass constructor\n writable: safeDescriptors ? false : true\n };\n}\n\nfunction createFlowAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$2,\n extend_: extend_$2,\n decorate_20223_: decorate_20223_$2\n };\n}\nfunction make_$2(adm, key, descriptor, source) {\n var _this$options_;\n // own\n if (source === adm.target_) {\n return this.extend_(adm, key, descriptor, false) === null ? 0 /* MakeResult.Cancel */ : 2 /* MakeResult.Continue */;\n }\n // prototype\n // bound - must annotate protos to support super.flow()\n if ((_this$options_ = this.options_) != null && _this$options_.bound && (!hasProp(adm.target_, key) || !isFlow(adm.target_[key]))) {\n if (this.extend_(adm, key, descriptor, false) === null) {\n return 0 /* MakeResult.Cancel */;\n }\n }\n\n if (isFlow(descriptor.value)) {\n // A prototype could have been annotated already by other constructor,\n // rest of the proto chain must be annotated already\n return 1 /* MakeResult.Break */;\n }\n\n var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, false, false);\n defineProperty(source, key, flowDescriptor);\n return 2 /* MakeResult.Continue */;\n}\n\nfunction extend_$2(adm, key, descriptor, proxyTrap) {\n var _this$options_2;\n var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, (_this$options_2 = this.options_) == null ? void 0 : _this$options_2.bound);\n return adm.defineProperty_(key, flowDescriptor, proxyTrap);\n}\nfunction decorate_20223_$2(mthd, context) {\n var _this$options_3;\n if (process.env.NODE_ENV !== \"production\") {\n assert20223DecoratorType(context, [\"method\"]);\n }\n var name = context.name,\n addInitializer = context.addInitializer;\n if (!isFlow(mthd)) {\n mthd = flow(mthd);\n }\n if ((_this$options_3 = this.options_) != null && _this$options_3.bound) {\n addInitializer(function () {\n var self = this;\n var bound = self[name].bind(self);\n bound.isMobXFlow = true;\n self[name] = bound;\n });\n }\n return mthd;\n}\nfunction assertFlowDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var value = _ref2.value;\n if (process.env.NODE_ENV !== \"production\" && !isFunction(value)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on properties with a generator function value.\"));\n }\n}\nfunction createFlowDescriptor(adm, annotation, key, descriptor, bound,\n// provides ability to disable safeDescriptors for prototypes\nsafeDescriptors) {\n if (safeDescriptors === void 0) {\n safeDescriptors = globalState.safeDescriptors;\n }\n assertFlowDescriptor(adm, annotation, key, descriptor);\n var value = descriptor.value;\n // In case of flow.bound, the descriptor can be from already annotated prototype\n if (!isFlow(value)) {\n value = flow(value);\n }\n if (bound) {\n var _adm$proxy_;\n // We do not keep original function around, so we bind the existing flow\n value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n // This is normally set by `flow`, but `bind` returns new function...\n value.isMobXFlow = true;\n }\n return {\n value: value,\n // Non-configurable for classes\n // prevents accidental field redefinition in subclass\n configurable: safeDescriptors ? adm.isPlainObject_ : true,\n // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058\n enumerable: false,\n // Non-obsevable, therefore non-writable\n // Also prevents rewriting in subclass constructor\n writable: safeDescriptors ? false : true\n };\n}\n\nfunction createComputedAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$3,\n extend_: extend_$3,\n decorate_20223_: decorate_20223_$3\n };\n}\nfunction make_$3(adm, key, descriptor) {\n return this.extend_(adm, key, descriptor, false) === null ? 0 /* MakeResult.Cancel */ : 1 /* MakeResult.Break */;\n}\n\nfunction extend_$3(adm, key, descriptor, proxyTrap) {\n assertComputedDescriptor(adm, this, key, descriptor);\n return adm.defineComputedProperty_(key, _extends({}, this.options_, {\n get: descriptor.get,\n set: descriptor.set\n }), proxyTrap);\n}\nfunction decorate_20223_$3(get, context) {\n if (process.env.NODE_ENV !== \"production\") {\n assert20223DecoratorType(context, [\"getter\"]);\n }\n var ann = this;\n var key = context.name,\n addInitializer = context.addInitializer;\n addInitializer(function () {\n var adm = asObservableObject(this)[$mobx];\n var options = _extends({}, ann.options_, {\n get: get,\n context: this\n });\n options.name || (options.name = process.env.NODE_ENV !== \"production\" ? adm.name_ + \".\" + key.toString() : \"ObservableObject.\" + key.toString());\n adm.values_.set(key, new ComputedValue(options));\n });\n return function () {\n return this[$mobx].getObservablePropValue_(key);\n };\n}\nfunction assertComputedDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var get = _ref2.get;\n if (process.env.NODE_ENV !== \"production\" && !get) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on getter(+setter) properties.\"));\n }\n}\n\nfunction createObservableAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$4,\n extend_: extend_$4,\n decorate_20223_: decorate_20223_$4\n };\n}\nfunction make_$4(adm, key, descriptor) {\n return this.extend_(adm, key, descriptor, false) === null ? 0 /* MakeResult.Cancel */ : 1 /* MakeResult.Break */;\n}\n\nfunction extend_$4(adm, key, descriptor, proxyTrap) {\n var _this$options_$enhanc, _this$options_;\n assertObservableDescriptor(adm, this, key, descriptor);\n return adm.defineObservableProperty_(key, descriptor.value, (_this$options_$enhanc = (_this$options_ = this.options_) == null ? void 0 : _this$options_.enhancer) != null ? _this$options_$enhanc : deepEnhancer, proxyTrap);\n}\nfunction decorate_20223_$4(desc, context) {\n if (process.env.NODE_ENV !== \"production\") {\n if (context.kind === \"field\") {\n throw die(\"Please use `@observable accessor \" + String(context.name) + \"` instead of `@observable \" + String(context.name) + \"`\");\n }\n assert20223DecoratorType(context, [\"accessor\"]);\n }\n var ann = this;\n var kind = context.kind,\n name = context.name;\n // The laziness here is not ideal... It's a workaround to how 2022.3 Decorators are implemented:\n // `addInitializer` callbacks are executed _before_ any accessors are defined (instead of the ideal-for-us right after each).\n // This means that, if we were to do our stuff in an `addInitializer`, we'd attempt to read a private slot\n // before it has been initialized. The runtime doesn't like that and throws a `Cannot read private member\n // from an object whose class did not declare it` error.\n // TODO: it seems that this will not be required anymore in the final version of the spec\n // See TODO: link\n var initializedObjects = new WeakSet();\n function initializeObservable(target, value) {\n var _ann$options_$enhance, _ann$options_;\n var adm = asObservableObject(target)[$mobx];\n var observable = new ObservableValue(value, (_ann$options_$enhance = (_ann$options_ = ann.options_) == null ? void 0 : _ann$options_.enhancer) != null ? _ann$options_$enhance : deepEnhancer, process.env.NODE_ENV !== \"production\" ? adm.name_ + \".\" + name.toString() : \"ObservableObject.\" + name.toString(), false);\n adm.values_.set(name, observable);\n initializedObjects.add(target);\n }\n if (kind == \"accessor\") {\n return {\n get: function get() {\n if (!initializedObjects.has(this)) {\n initializeObservable(this, desc.get.call(this));\n }\n return this[$mobx].getObservablePropValue_(name);\n },\n set: function set(value) {\n if (!initializedObjects.has(this)) {\n initializeObservable(this, value);\n }\n return this[$mobx].setObservablePropValue_(name, value);\n },\n init: function init(value) {\n if (!initializedObjects.has(this)) {\n initializeObservable(this, value);\n }\n return value;\n }\n };\n }\n return;\n}\nfunction assertObservableDescriptor(adm, _ref, key, descriptor) {\n var annotationType_ = _ref.annotationType_;\n if (process.env.NODE_ENV !== \"production\" && !(\"value\" in descriptor)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' cannot be used on getter/setter properties\"));\n }\n}\n\nvar AUTO = \"true\";\nvar autoAnnotation = /*#__PURE__*/createAutoAnnotation();\nfunction createAutoAnnotation(options) {\n return {\n annotationType_: AUTO,\n options_: options,\n make_: make_$5,\n extend_: extend_$5,\n decorate_20223_: decorate_20223_$5\n };\n}\nfunction make_$5(adm, key, descriptor, source) {\n var _this$options_3, _this$options_4;\n // getter -> computed\n if (descriptor.get) {\n return computed.make_(adm, key, descriptor, source);\n }\n // lone setter -> action setter\n if (descriptor.set) {\n // TODO make action applicable to setter and delegate to action.make_\n var set = createAction(key.toString(), descriptor.set);\n // own\n if (source === adm.target_) {\n return adm.defineProperty_(key, {\n configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,\n set: set\n }) === null ? 0 /* MakeResult.Cancel */ : 2 /* MakeResult.Continue */;\n }\n // proto\n defineProperty(source, key, {\n configurable: true,\n set: set\n });\n return 2 /* MakeResult.Continue */;\n }\n // function on proto -> autoAction/flow\n if (source !== adm.target_ && typeof descriptor.value === \"function\") {\n var _this$options_2;\n if (isGenerator(descriptor.value)) {\n var _this$options_;\n var flowAnnotation = (_this$options_ = this.options_) != null && _this$options_.autoBind ? flow.bound : flow;\n return flowAnnotation.make_(adm, key, descriptor, source);\n }\n var actionAnnotation = (_this$options_2 = this.options_) != null && _this$options_2.autoBind ? autoAction.bound : autoAction;\n return actionAnnotation.make_(adm, key, descriptor, source);\n }\n // other -> observable\n // Copy props from proto as well, see test:\n // \"decorate should work with Object.create\"\n var observableAnnotation = ((_this$options_3 = this.options_) == null ? void 0 : _this$options_3.deep) === false ? observable.ref : observable;\n // if function respect autoBind option\n if (typeof descriptor.value === \"function\" && (_this$options_4 = this.options_) != null && _this$options_4.autoBind) {\n var _adm$proxy_;\n descriptor.value = descriptor.value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n }\n return observableAnnotation.make_(adm, key, descriptor, source);\n}\nfunction extend_$5(adm, key, descriptor, proxyTrap) {\n var _this$options_5, _this$options_6;\n // getter -> computed\n if (descriptor.get) {\n return computed.extend_(adm, key, descriptor, proxyTrap);\n }\n // lone setter -> action setter\n if (descriptor.set) {\n // TODO make action applicable to setter and delegate to action.extend_\n return adm.defineProperty_(key, {\n configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,\n set: createAction(key.toString(), descriptor.set)\n }, proxyTrap);\n }\n // other -> observable\n // if function respect autoBind option\n if (typeof descriptor.value === \"function\" && (_this$options_5 = this.options_) != null && _this$options_5.autoBind) {\n var _adm$proxy_2;\n descriptor.value = descriptor.value.bind((_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_);\n }\n var observableAnnotation = ((_this$options_6 = this.options_) == null ? void 0 : _this$options_6.deep) === false ? observable.ref : observable;\n return observableAnnotation.extend_(adm, key, descriptor, proxyTrap);\n}\nfunction decorate_20223_$5(desc, context) {\n die(\"'\" + this.annotationType_ + \"' cannot be used as a decorator\");\n}\n\nvar OBSERVABLE = \"observable\";\nvar OBSERVABLE_REF = \"observable.ref\";\nvar OBSERVABLE_SHALLOW = \"observable.shallow\";\nvar OBSERVABLE_STRUCT = \"observable.struct\";\n// Predefined bags of create observable options, to avoid allocating temporarily option objects\n// in the majority of cases\nvar defaultCreateObservableOptions = {\n deep: true,\n name: undefined,\n defaultDecorator: undefined,\n proxy: true\n};\nObject.freeze(defaultCreateObservableOptions);\nfunction asCreateObservableOptions(thing) {\n return thing || defaultCreateObservableOptions;\n}\nvar observableAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE);\nvar observableRefAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_REF, {\n enhancer: referenceEnhancer\n});\nvar observableShallowAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_SHALLOW, {\n enhancer: shallowEnhancer\n});\nvar observableStructAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_STRUCT, {\n enhancer: refStructEnhancer\n});\nvar observableDecoratorAnnotation = /*#__PURE__*/createDecoratorAnnotation(observableAnnotation);\nfunction getEnhancerFromOptions(options) {\n return options.deep === true ? deepEnhancer : options.deep === false ? referenceEnhancer : getEnhancerFromAnnotation(options.defaultDecorator);\n}\nfunction getAnnotationFromOptions(options) {\n var _options$defaultDecor;\n return options ? (_options$defaultDecor = options.defaultDecorator) != null ? _options$defaultDecor : createAutoAnnotation(options) : undefined;\n}\nfunction getEnhancerFromAnnotation(annotation) {\n var _annotation$options_$, _annotation$options_;\n return !annotation ? deepEnhancer : (_annotation$options_$ = (_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.enhancer) != null ? _annotation$options_$ : deepEnhancer;\n}\n/**\n * Turns an object, array or function into a reactive structure.\n * @param v the value which should become observable.\n */\nfunction createObservable(v, arg2, arg3) {\n // @observable someProp; (2022.3 Decorators)\n if (is20223Decorator(arg2)) {\n return observableAnnotation.decorate_20223_(v, arg2);\n }\n // @observable someProp;\n if (isStringish(arg2)) {\n storeAnnotation(v, arg2, observableAnnotation);\n return;\n }\n // already observable - ignore\n if (isObservable(v)) {\n return v;\n }\n // plain object\n if (isPlainObject(v)) {\n return observable.object(v, arg2, arg3);\n }\n // Array\n if (Array.isArray(v)) {\n return observable.array(v, arg2);\n }\n // Map\n if (isES6Map(v)) {\n return observable.map(v, arg2);\n }\n // Set\n if (isES6Set(v)) {\n return observable.set(v, arg2);\n }\n // other object - ignore\n if (typeof v === \"object\" && v !== null) {\n return v;\n }\n // anything else\n return observable.box(v, arg2);\n}\nassign(createObservable, observableDecoratorAnnotation);\nvar observableFactories = {\n box: function box(value, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableValue(value, getEnhancerFromOptions(o), o.name, true, o.equals);\n },\n array: function array(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return (globalState.useProxies === false || o.proxy === false ? createLegacyArray : createObservableArray)(initialValues, getEnhancerFromOptions(o), o.name);\n },\n map: function map(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableMap(initialValues, getEnhancerFromOptions(o), o.name);\n },\n set: function set(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableSet(initialValues, getEnhancerFromOptions(o), o.name);\n },\n object: function object(props, decorators, options) {\n return initObservable(function () {\n return extendObservable(globalState.useProxies === false || (options == null ? void 0 : options.proxy) === false ? asObservableObject({}, options) : asDynamicObservableObject({}, options), props, decorators);\n });\n },\n ref: /*#__PURE__*/createDecoratorAnnotation(observableRefAnnotation),\n shallow: /*#__PURE__*/createDecoratorAnnotation(observableShallowAnnotation),\n deep: observableDecoratorAnnotation,\n struct: /*#__PURE__*/createDecoratorAnnotation(observableStructAnnotation)\n};\n// eslint-disable-next-line\nvar observable = /*#__PURE__*/assign(createObservable, observableFactories);\n\nvar COMPUTED = \"computed\";\nvar COMPUTED_STRUCT = \"computed.struct\";\nvar computedAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED);\nvar computedStructAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED_STRUCT, {\n equals: comparer.structural\n});\n/**\n * Decorator for class properties: @computed get value() { return expr; }.\n * For legacy purposes also invokable as ES5 observable created: `computed(() => expr)`;\n */\nvar computed = function computed(arg1, arg2) {\n if (is20223Decorator(arg2)) {\n // @computed (2022.3 Decorators)\n return computedAnnotation.decorate_20223_(arg1, arg2);\n }\n if (isStringish(arg2)) {\n // @computed\n return storeAnnotation(arg1, arg2, computedAnnotation);\n }\n if (isPlainObject(arg1)) {\n // @computed({ options })\n return createDecoratorAnnotation(createComputedAnnotation(COMPUTED, arg1));\n }\n // computed(expr, options?)\n if (process.env.NODE_ENV !== \"production\") {\n if (!isFunction(arg1)) {\n die(\"First argument to `computed` should be an expression.\");\n }\n if (isFunction(arg2)) {\n die(\"A setter as second argument is no longer supported, use `{ set: fn }` option instead\");\n }\n }\n var opts = isPlainObject(arg2) ? arg2 : {};\n opts.get = arg1;\n opts.name || (opts.name = arg1.name || \"\"); /* for generated name */\n return new ComputedValue(opts);\n};\nObject.assign(computed, computedAnnotation);\ncomputed.struct = /*#__PURE__*/createDecoratorAnnotation(computedStructAnnotation);\n\nvar _getDescriptor$config, _getDescriptor;\n// we don't use globalState for these in order to avoid possible issues with multiple\n// mobx versions\nvar currentActionId = 0;\nvar nextActionId = 1;\nvar isFunctionNameConfigurable = (_getDescriptor$config = (_getDescriptor = /*#__PURE__*/getDescriptor(function () {}, \"name\")) == null ? void 0 : _getDescriptor.configurable) != null ? _getDescriptor$config : false;\n// we can safely recycle this object\nvar tmpNameDescriptor = {\n value: \"action\",\n configurable: true,\n writable: false,\n enumerable: false\n};\nfunction createAction(actionName, fn, autoAction, ref) {\n if (autoAction === void 0) {\n autoAction = false;\n }\n if (process.env.NODE_ENV !== \"production\") {\n if (!isFunction(fn)) {\n die(\"`action` can only be invoked on functions\");\n }\n if (typeof actionName !== \"string\" || !actionName) {\n die(\"actions should have valid names, got: '\" + actionName + \"'\");\n }\n }\n function res() {\n return executeAction(actionName, autoAction, fn, ref || this, arguments);\n }\n res.isMobxAction = true;\n res.toString = function () {\n return fn.toString();\n };\n if (isFunctionNameConfigurable) {\n tmpNameDescriptor.value = actionName;\n defineProperty(res, \"name\", tmpNameDescriptor);\n }\n return res;\n}\nfunction executeAction(actionName, canRunAsDerivation, fn, scope, args) {\n var runInfo = _startAction(actionName, canRunAsDerivation, scope, args);\n try {\n return fn.apply(scope, args);\n } catch (err) {\n runInfo.error_ = err;\n throw err;\n } finally {\n _endAction(runInfo);\n }\n}\nfunction _startAction(actionName, canRunAsDerivation,\n// true for autoAction\nscope, args) {\n var notifySpy_ = process.env.NODE_ENV !== \"production\" && isSpyEnabled() && !!actionName;\n var startTime_ = 0;\n if (process.env.NODE_ENV !== \"production\" && notifySpy_) {\n startTime_ = Date.now();\n var flattenedArgs = args ? Array.from(args) : EMPTY_ARRAY;\n spyReportStart({\n type: ACTION,\n name: actionName,\n object: scope,\n arguments: flattenedArgs\n });\n }\n var prevDerivation_ = globalState.trackingDerivation;\n var runAsAction = !canRunAsDerivation || !prevDerivation_;\n startBatch();\n var prevAllowStateChanges_ = globalState.allowStateChanges; // by default preserve previous allow\n if (runAsAction) {\n untrackedStart();\n prevAllowStateChanges_ = allowStateChangesStart(true);\n }\n var prevAllowStateReads_ = allowStateReadsStart(true);\n var runInfo = {\n runAsAction_: runAsAction,\n prevDerivation_: prevDerivation_,\n prevAllowStateChanges_: prevAllowStateChanges_,\n prevAllowStateReads_: prevAllowStateReads_,\n notifySpy_: notifySpy_,\n startTime_: startTime_,\n actionId_: nextActionId++,\n parentActionId_: currentActionId\n };\n currentActionId = runInfo.actionId_;\n return runInfo;\n}\nfunction _endAction(runInfo) {\n if (currentActionId !== runInfo.actionId_) {\n die(30);\n }\n currentActionId = runInfo.parentActionId_;\n if (runInfo.error_ !== undefined) {\n globalState.suppressReactionErrors = true;\n }\n allowStateChangesEnd(runInfo.prevAllowStateChanges_);\n allowStateReadsEnd(runInfo.prevAllowStateReads_);\n endBatch();\n if (runInfo.runAsAction_) {\n untrackedEnd(runInfo.prevDerivation_);\n }\n if (process.env.NODE_ENV !== \"production\" && runInfo.notifySpy_) {\n spyReportEnd({\n time: Date.now() - runInfo.startTime_\n });\n }\n globalState.suppressReactionErrors = false;\n}\nfunction allowStateChanges(allowStateChanges, func) {\n var prev = allowStateChangesStart(allowStateChanges);\n try {\n return func();\n } finally {\n allowStateChangesEnd(prev);\n }\n}\nfunction allowStateChangesStart(allowStateChanges) {\n var prev = globalState.allowStateChanges;\n globalState.allowStateChanges = allowStateChanges;\n return prev;\n}\nfunction allowStateChangesEnd(prev) {\n globalState.allowStateChanges = prev;\n}\n\nvar _Symbol$toPrimitive;\nvar CREATE = \"create\";\n_Symbol$toPrimitive = Symbol.toPrimitive;\nvar ObservableValue = /*#__PURE__*/function (_Atom) {\n _inheritsLoose(ObservableValue, _Atom);\n function ObservableValue(value, enhancer, name_, notifySpy, equals) {\n var _this;\n if (name_ === void 0) {\n name_ = process.env.NODE_ENV !== \"production\" ? \"ObservableValue@\" + getNextId() : \"ObservableValue\";\n }\n if (notifySpy === void 0) {\n notifySpy = true;\n }\n if (equals === void 0) {\n equals = comparer[\"default\"];\n }\n _this = _Atom.call(this, name_) || this;\n _this.enhancer = void 0;\n _this.name_ = void 0;\n _this.equals = void 0;\n _this.hasUnreportedChange_ = false;\n _this.interceptors_ = void 0;\n _this.changeListeners_ = void 0;\n _this.value_ = void 0;\n _this.dehancer = void 0;\n _this.enhancer = enhancer;\n _this.name_ = name_;\n _this.equals = equals;\n _this.value_ = enhancer(value, undefined, name_);\n if (process.env.NODE_ENV !== \"production\" && notifySpy && isSpyEnabled()) {\n // only notify spy if this is a stand-alone observable\n spyReport({\n type: CREATE,\n object: _assertThisInitialized(_this),\n observableKind: \"value\",\n debugObjectName: _this.name_,\n newValue: \"\" + _this.value_\n });\n }\n return _this;\n }\n var _proto = ObservableValue.prototype;\n _proto.dehanceValue = function dehanceValue(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n return value;\n };\n _proto.set = function set(newValue) {\n var oldValue = this.value_;\n newValue = this.prepareNewValue_(newValue);\n if (newValue !== globalState.UNCHANGED) {\n var notifySpy = isSpyEnabled();\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart({\n type: UPDATE,\n object: this,\n observableKind: \"value\",\n debugObjectName: this.name_,\n newValue: newValue,\n oldValue: oldValue\n });\n }\n this.setNewValue_(newValue);\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n }\n };\n _proto.prepareNewValue_ = function prepareNewValue_(newValue) {\n checkIfStateModificationsAreAllowed(this);\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this,\n type: UPDATE,\n newValue: newValue\n });\n if (!change) {\n return globalState.UNCHANGED;\n }\n newValue = change.newValue;\n }\n // apply modifier\n newValue = this.enhancer(newValue, this.value_, this.name_);\n return this.equals(this.value_, newValue) ? globalState.UNCHANGED : newValue;\n };\n _proto.setNewValue_ = function setNewValue_(newValue) {\n var oldValue = this.value_;\n this.value_ = newValue;\n this.reportChanged();\n if (hasListeners(this)) {\n notifyListeners(this, {\n type: UPDATE,\n object: this,\n newValue: newValue,\n oldValue: oldValue\n });\n }\n };\n _proto.get = function get() {\n this.reportObserved();\n return this.dehanceValue(this.value_);\n };\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (fireImmediately) {\n listener({\n observableKind: \"value\",\n debugObjectName: this.name_,\n object: this,\n type: UPDATE,\n newValue: this.value_,\n oldValue: undefined\n });\n }\n return registerListener(this, listener);\n };\n _proto.raw = function raw() {\n // used by MST ot get undehanced value\n return this.value_;\n };\n _proto.toJSON = function toJSON() {\n return this.get();\n };\n _proto.toString = function toString() {\n return this.name_ + \"[\" + this.value_ + \"]\";\n };\n _proto.valueOf = function valueOf() {\n return toPrimitive(this.get());\n };\n _proto[_Symbol$toPrimitive] = function () {\n return this.valueOf();\n };\n return ObservableValue;\n}(Atom);\nvar isObservableValue = /*#__PURE__*/createInstanceofPredicate(\"ObservableValue\", ObservableValue);\n\nvar _Symbol$toPrimitive$1;\n/**\n * A node in the state dependency root that observes other nodes, and can be observed itself.\n *\n * ComputedValue will remember the result of the computation for the duration of the batch, or\n * while being observed.\n *\n * During this time it will recompute only when one of its direct dependencies changed,\n * but only when it is being accessed with `ComputedValue.get()`.\n *\n * Implementation description:\n * 1. First time it's being accessed it will compute and remember result\n * give back remembered result until 2. happens\n * 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3.\n * 3. When it's being accessed, recompute if any shallow dependency changed.\n * if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step.\n * go to step 2. either way\n *\n * If at any point it's outside batch and it isn't observed: reset everything and go to 1.\n */\n_Symbol$toPrimitive$1 = Symbol.toPrimitive;\nvar ComputedValue = /*#__PURE__*/function () {\n // nodes we are looking at. Our value depends on these nodes\n // during tracking it's an array with new observed observers\n\n // to check for cycles\n\n // N.B: unminified as it is used by MST\n\n /**\n * Create a new computed value based on a function expression.\n *\n * The `name` property is for debug purposes only.\n *\n * The `equals` property specifies the comparer function to use to determine if a newly produced\n * value differs from the previous value. Two comparers are provided in the library; `defaultComparer`\n * compares based on identity comparison (===), and `structuralComparer` deeply compares the structure.\n * Structural comparison can be convenient if you always produce a new aggregated object and\n * don't want to notify observers if it is structurally the same.\n * This is useful for working with vectors, mouse coordinates etc.\n */\n function ComputedValue(options) {\n this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n this.observing_ = [];\n this.newObserving_ = null;\n this.isBeingObserved_ = false;\n this.isPendingUnobservation_ = false;\n this.observers_ = new Set();\n this.diffValue_ = 0;\n this.runId_ = 0;\n this.lastAccessedBy_ = 0;\n this.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n this.unboundDepsCount_ = 0;\n this.value_ = new CaughtException(null);\n this.name_ = void 0;\n this.triggeredBy_ = void 0;\n this.isComputing_ = false;\n this.isRunningSetter_ = false;\n this.derivation = void 0;\n this.setter_ = void 0;\n this.isTracing_ = TraceMode.NONE;\n this.scope_ = void 0;\n this.equals_ = void 0;\n this.requiresReaction_ = void 0;\n this.keepAlive_ = void 0;\n this.onBOL = void 0;\n this.onBUOL = void 0;\n if (!options.get) {\n die(31);\n }\n this.derivation = options.get;\n this.name_ = options.name || (process.env.NODE_ENV !== \"production\" ? \"ComputedValue@\" + getNextId() : \"ComputedValue\");\n if (options.set) {\n this.setter_ = createAction(process.env.NODE_ENV !== \"production\" ? this.name_ + \"-setter\" : \"ComputedValue-setter\", options.set);\n }\n this.equals_ = options.equals || (options.compareStructural || options.struct ? comparer.structural : comparer[\"default\"]);\n this.scope_ = options.context;\n this.requiresReaction_ = options.requiresReaction;\n this.keepAlive_ = !!options.keepAlive;\n }\n var _proto = ComputedValue.prototype;\n _proto.onBecomeStale_ = function onBecomeStale_() {\n propagateMaybeChanged(this);\n };\n _proto.onBO = function onBO() {\n if (this.onBOL) {\n this.onBOL.forEach(function (listener) {\n return listener();\n });\n }\n };\n _proto.onBUO = function onBUO() {\n if (this.onBUOL) {\n this.onBUOL.forEach(function (listener) {\n return listener();\n });\n }\n }\n /**\n * Returns the current value of this computed value.\n * Will evaluate its computation first if needed.\n */;\n _proto.get = function get() {\n if (this.isComputing_) {\n die(32, this.name_, this.derivation);\n }\n if (globalState.inBatch === 0 &&\n // !globalState.trackingDerivatpion &&\n this.observers_.size === 0 && !this.keepAlive_) {\n if (shouldCompute(this)) {\n this.warnAboutUntrackedRead_();\n startBatch(); // See perf test 'computed memoization'\n this.value_ = this.computeValue_(false);\n endBatch();\n }\n } else {\n reportObserved(this);\n if (shouldCompute(this)) {\n var prevTrackingContext = globalState.trackingContext;\n if (this.keepAlive_ && !prevTrackingContext) {\n globalState.trackingContext = this;\n }\n if (this.trackAndCompute()) {\n propagateChangeConfirmed(this);\n }\n globalState.trackingContext = prevTrackingContext;\n }\n }\n var result = this.value_;\n if (isCaughtException(result)) {\n throw result.cause;\n }\n return result;\n };\n _proto.set = function set(value) {\n if (this.setter_) {\n if (this.isRunningSetter_) {\n die(33, this.name_);\n }\n this.isRunningSetter_ = true;\n try {\n this.setter_.call(this.scope_, value);\n } finally {\n this.isRunningSetter_ = false;\n }\n } else {\n die(34, this.name_);\n }\n };\n _proto.trackAndCompute = function trackAndCompute() {\n // N.B: unminified as it is used by MST\n var oldValue = this.value_;\n var wasSuspended = /* see #1208 */this.dependenciesState_ === IDerivationState_.NOT_TRACKING_;\n var newValue = this.computeValue_(true);\n var changed = wasSuspended || isCaughtException(oldValue) || isCaughtException(newValue) || !this.equals_(oldValue, newValue);\n if (changed) {\n this.value_ = newValue;\n if (process.env.NODE_ENV !== \"production\" && isSpyEnabled()) {\n spyReport({\n observableKind: \"computed\",\n debugObjectName: this.name_,\n object: this.scope_,\n type: \"update\",\n oldValue: oldValue,\n newValue: newValue\n });\n }\n }\n return changed;\n };\n _proto.computeValue_ = function computeValue_(track) {\n this.isComputing_ = true;\n // don't allow state changes during computation\n var prev = allowStateChangesStart(false);\n var res;\n if (track) {\n res = trackDerivedFunction(this, this.derivation, this.scope_);\n } else {\n if (globalState.disableErrorBoundaries === true) {\n res = this.derivation.call(this.scope_);\n } else {\n try {\n res = this.derivation.call(this.scope_);\n } catch (e) {\n res = new CaughtException(e);\n }\n }\n }\n allowStateChangesEnd(prev);\n this.isComputing_ = false;\n return res;\n };\n _proto.suspend_ = function suspend_() {\n if (!this.keepAlive_) {\n clearObserving(this);\n this.value_ = undefined; // don't hold on to computed value!\n if (process.env.NODE_ENV !== \"production\" && this.isTracing_ !== TraceMode.NONE) {\n console.log(\"[mobx.trace] Computed value '\" + this.name_ + \"' was suspended and it will recompute on the next access.\");\n }\n }\n };\n _proto.observe_ = function observe_(listener, fireImmediately) {\n var _this = this;\n var firstTime = true;\n var prevValue = undefined;\n return autorun(function () {\n // TODO: why is this in a different place than the spyReport() function? in all other observables it's called in the same place\n var newValue = _this.get();\n if (!firstTime || fireImmediately) {\n var prevU = untrackedStart();\n listener({\n observableKind: \"computed\",\n debugObjectName: _this.name_,\n type: UPDATE,\n object: _this,\n newValue: newValue,\n oldValue: prevValue\n });\n untrackedEnd(prevU);\n }\n firstTime = false;\n prevValue = newValue;\n });\n };\n _proto.warnAboutUntrackedRead_ = function warnAboutUntrackedRead_() {\n if (!(process.env.NODE_ENV !== \"production\")) {\n return;\n }\n if (this.isTracing_ !== TraceMode.NONE) {\n console.log(\"[mobx.trace] Computed value '\" + this.name_ + \"' is being read outside a reactive context. Doing a full recompute.\");\n }\n if (typeof this.requiresReaction_ === \"boolean\" ? this.requiresReaction_ : globalState.computedRequiresReaction) {\n console.warn(\"[mobx] Computed value '\" + this.name_ + \"' is being read outside a reactive context. Doing a full recompute.\");\n }\n };\n _proto.toString = function toString() {\n return this.name_ + \"[\" + this.derivation.toString() + \"]\";\n };\n _proto.valueOf = function valueOf() {\n return toPrimitive(this.get());\n };\n _proto[_Symbol$toPrimitive$1] = function () {\n return this.valueOf();\n };\n return ComputedValue;\n}();\nvar isComputedValue = /*#__PURE__*/createInstanceofPredicate(\"ComputedValue\", ComputedValue);\n\nvar IDerivationState_;\n(function (IDerivationState_) {\n // before being run or (outside batch and not being observed)\n // at this point derivation is not holding any data about dependency tree\n IDerivationState_[IDerivationState_[\"NOT_TRACKING_\"] = -1] = \"NOT_TRACKING_\";\n // no shallow dependency changed since last computation\n // won't recalculate derivation\n // this is what makes mobx fast\n IDerivationState_[IDerivationState_[\"UP_TO_DATE_\"] = 0] = \"UP_TO_DATE_\";\n // some deep dependency changed, but don't know if shallow dependency changed\n // will require to check first if UP_TO_DATE or POSSIBLY_STALE\n // currently only ComputedValue will propagate POSSIBLY_STALE\n //\n // having this state is second big optimization:\n // don't have to recompute on every dependency change, but only when it's needed\n IDerivationState_[IDerivationState_[\"POSSIBLY_STALE_\"] = 1] = \"POSSIBLY_STALE_\";\n // A shallow dependency has changed since last computation and the derivation\n // will need to recompute when it's needed next.\n IDerivationState_[IDerivationState_[\"STALE_\"] = 2] = \"STALE_\";\n})(IDerivationState_ || (IDerivationState_ = {}));\nvar TraceMode;\n(function (TraceMode) {\n TraceMode[TraceMode[\"NONE\"] = 0] = \"NONE\";\n TraceMode[TraceMode[\"LOG\"] = 1] = \"LOG\";\n TraceMode[TraceMode[\"BREAK\"] = 2] = \"BREAK\";\n})(TraceMode || (TraceMode = {}));\nvar CaughtException = function CaughtException(cause) {\n this.cause = void 0;\n this.cause = cause;\n // Empty\n};\n\nfunction isCaughtException(e) {\n return e instanceof CaughtException;\n}\n/**\n * Finds out whether any dependency of the derivation has actually changed.\n * If dependenciesState is 1 then it will recalculate dependencies,\n * if any dependency changed it will propagate it by changing dependenciesState to 2.\n *\n * By iterating over the dependencies in the same order that they were reported and\n * stopping on the first change, all the recalculations are only called for ComputedValues\n * that will be tracked by derivation. That is because we assume that if the first x\n * dependencies of the derivation doesn't change then the derivation should run the same way\n * up until accessing x-th dependency.\n */\nfunction shouldCompute(derivation) {\n switch (derivation.dependenciesState_) {\n case IDerivationState_.UP_TO_DATE_:\n return false;\n case IDerivationState_.NOT_TRACKING_:\n case IDerivationState_.STALE_:\n return true;\n case IDerivationState_.POSSIBLY_STALE_:\n {\n // state propagation can occur outside of action/reactive context #2195\n var prevAllowStateReads = allowStateReadsStart(true);\n var prevUntracked = untrackedStart(); // no need for those computeds to be reported, they will be picked up in trackDerivedFunction.\n var obs = derivation.observing_,\n l = obs.length;\n for (var i = 0; i < l; i++) {\n var obj = obs[i];\n if (isComputedValue(obj)) {\n if (globalState.disableErrorBoundaries) {\n obj.get();\n } else {\n try {\n obj.get();\n } catch (e) {\n // we are not interested in the value *or* exception at this moment, but if there is one, notify all\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return true;\n }\n }\n // if ComputedValue `obj` actually changed it will be computed and propagated to its observers.\n // and `derivation` is an observer of `obj`\n // invariantShouldCompute(derivation)\n if (derivation.dependenciesState_ === IDerivationState_.STALE_) {\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return true;\n }\n }\n }\n changeDependenciesStateTo0(derivation);\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return false;\n }\n }\n}\nfunction isComputingDerivation() {\n return globalState.trackingDerivation !== null; // filter out actions inside computations\n}\n\nfunction checkIfStateModificationsAreAllowed(atom) {\n if (!(process.env.NODE_ENV !== \"production\")) {\n return;\n }\n var hasObservers = atom.observers_.size > 0;\n // Should not be possible to change observed state outside strict mode, except during initialization, see #563\n if (!globalState.allowStateChanges && (hasObservers || globalState.enforceActions === \"always\")) {\n console.warn(\"[MobX] \" + (globalState.enforceActions ? \"Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: \" : \"Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: \") + atom.name_);\n }\n}\nfunction checkIfStateReadsAreAllowed(observable) {\n if (process.env.NODE_ENV !== \"production\" && !globalState.allowStateReads && globalState.observableRequiresReaction) {\n console.warn(\"[mobx] Observable '\" + observable.name_ + \"' being read outside a reactive context.\");\n }\n}\n/**\n * Executes the provided function `f` and tracks which observables are being accessed.\n * The tracking information is stored on the `derivation` object and the derivation is registered\n * as observer of any of the accessed observables.\n */\nfunction trackDerivedFunction(derivation, f, context) {\n var prevAllowStateReads = allowStateReadsStart(true);\n // pre allocate array allocation + room for variation in deps\n // array will be trimmed by bindDependencies\n changeDependenciesStateTo0(derivation);\n derivation.newObserving_ = new Array(derivation.observing_.length + 100);\n derivation.unboundDepsCount_ = 0;\n derivation.runId_ = ++globalState.runId;\n var prevTracking = globalState.trackingDerivation;\n globalState.trackingDerivation = derivation;\n globalState.inBatch++;\n var result;\n if (globalState.disableErrorBoundaries === true) {\n result = f.call(context);\n } else {\n try {\n result = f.call(context);\n } catch (e) {\n result = new CaughtException(e);\n }\n }\n globalState.inBatch--;\n globalState.trackingDerivation = prevTracking;\n bindDependencies(derivation);\n warnAboutDerivationWithoutDependencies(derivation);\n allowStateReadsEnd(prevAllowStateReads);\n return result;\n}\nfunction warnAboutDerivationWithoutDependencies(derivation) {\n if (!(process.env.NODE_ENV !== \"production\")) {\n return;\n }\n if (derivation.observing_.length !== 0) {\n return;\n }\n if (typeof derivation.requiresObservable_ === \"boolean\" ? derivation.requiresObservable_ : globalState.reactionRequiresObservable) {\n console.warn(\"[mobx] Derivation '\" + derivation.name_ + \"' is created/updated without reading any observable value.\");\n }\n}\n/**\n * diffs newObserving with observing.\n * update observing to be newObserving with unique observables\n * notify observers that become observed/unobserved\n */\nfunction bindDependencies(derivation) {\n // invariant(derivation.dependenciesState !== IDerivationState.NOT_TRACKING, \"INTERNAL ERROR bindDependencies expects derivation.dependenciesState !== -1\");\n var prevObserving = derivation.observing_;\n var observing = derivation.observing_ = derivation.newObserving_;\n var lowestNewObservingDerivationState = IDerivationState_.UP_TO_DATE_;\n // Go through all new observables and check diffValue: (this list can contain duplicates):\n // 0: first occurrence, change to 1 and keep it\n // 1: extra occurrence, drop it\n var i0 = 0,\n l = derivation.unboundDepsCount_;\n for (var i = 0; i < l; i++) {\n var dep = observing[i];\n if (dep.diffValue_ === 0) {\n dep.diffValue_ = 1;\n if (i0 !== i) {\n observing[i0] = dep;\n }\n i0++;\n }\n // Upcast is 'safe' here, because if dep is IObservable, `dependenciesState` will be undefined,\n // not hitting the condition\n if (dep.dependenciesState_ > lowestNewObservingDerivationState) {\n lowestNewObservingDerivationState = dep.dependenciesState_;\n }\n }\n observing.length = i0;\n derivation.newObserving_ = null; // newObserving shouldn't be needed outside tracking (statement moved down to work around FF bug, see #614)\n // Go through all old observables and check diffValue: (it is unique after last bindDependencies)\n // 0: it's not in new observables, unobserve it\n // 1: it keeps being observed, don't want to notify it. change to 0\n l = prevObserving.length;\n while (l--) {\n var _dep = prevObserving[l];\n if (_dep.diffValue_ === 0) {\n removeObserver(_dep, derivation);\n }\n _dep.diffValue_ = 0;\n }\n // Go through all new observables and check diffValue: (now it should be unique)\n // 0: it was set to 0 in last loop. don't need to do anything.\n // 1: it wasn't observed, let's observe it. set back to 0\n while (i0--) {\n var _dep2 = observing[i0];\n if (_dep2.diffValue_ === 1) {\n _dep2.diffValue_ = 0;\n addObserver(_dep2, derivation);\n }\n }\n // Some new observed derivations may become stale during this derivation computation\n // so they have had no chance to propagate staleness (#916)\n if (lowestNewObservingDerivationState !== IDerivationState_.UP_TO_DATE_) {\n derivation.dependenciesState_ = lowestNewObservingDerivationState;\n derivation.onBecomeStale_();\n }\n}\nfunction clearObserving(derivation) {\n // invariant(globalState.inBatch > 0, \"INTERNAL ERROR clearObserving should be called only inside batch\");\n var obs = derivation.observing_;\n derivation.observing_ = [];\n var i = obs.length;\n while (i--) {\n removeObserver(obs[i], derivation);\n }\n derivation.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n}\nfunction untracked(action) {\n var prev = untrackedStart();\n try {\n return action();\n } finally {\n untrackedEnd(prev);\n }\n}\nfunction untrackedStart() {\n var prev = globalState.trackingDerivation;\n globalState.trackingDerivation = null;\n return prev;\n}\nfunction untrackedEnd(prev) {\n globalState.trackingDerivation = prev;\n}\nfunction allowStateReadsStart(allowStateReads) {\n var prev = globalState.allowStateReads;\n globalState.allowStateReads = allowStateReads;\n return prev;\n}\nfunction allowStateReadsEnd(prev) {\n globalState.allowStateReads = prev;\n}\n/**\n * needed to keep `lowestObserverState` correct. when changing from (2 or 1) to 0\n *\n */\nfunction changeDependenciesStateTo0(derivation) {\n if (derivation.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n return;\n }\n derivation.dependenciesState_ = IDerivationState_.UP_TO_DATE_;\n var obs = derivation.observing_;\n var i = obs.length;\n while (i--) {\n obs[i].lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n }\n}\n\n/**\n * These values will persist if global state is reset\n */\nvar persistentKeys = [\"mobxGuid\", \"spyListeners\", \"enforceActions\", \"computedRequiresReaction\", \"reactionRequiresObservable\", \"observableRequiresReaction\", \"allowStateReads\", \"disableErrorBoundaries\", \"runId\", \"UNCHANGED\", \"useProxies\"];\nvar MobXGlobals = function MobXGlobals() {\n this.version = 6;\n this.UNCHANGED = {};\n this.trackingDerivation = null;\n this.trackingContext = null;\n this.runId = 0;\n this.mobxGuid = 0;\n this.inBatch = 0;\n this.pendingUnobservations = [];\n this.pendingReactions = [];\n this.isRunningReactions = false;\n this.allowStateChanges = false;\n this.allowStateReads = true;\n this.enforceActions = true;\n this.spyListeners = [];\n this.globalReactionErrorHandlers = [];\n this.computedRequiresReaction = false;\n this.reactionRequiresObservable = false;\n this.observableRequiresReaction = false;\n this.disableErrorBoundaries = false;\n this.suppressReactionErrors = false;\n this.useProxies = true;\n this.verifyProxies = false;\n this.safeDescriptors = true;\n};\nvar canMergeGlobalState = true;\nvar isolateCalled = false;\nvar globalState = /*#__PURE__*/function () {\n var global = /*#__PURE__*/getGlobal();\n if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals) {\n canMergeGlobalState = false;\n }\n if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version) {\n canMergeGlobalState = false;\n }\n if (!canMergeGlobalState) {\n // Because this is a IIFE we need to let isolateCalled a chance to change\n // so we run it after the event loop completed at least 1 iteration\n setTimeout(function () {\n if (!isolateCalled) {\n die(35);\n }\n }, 1);\n return new MobXGlobals();\n } else if (global.__mobxGlobals) {\n global.__mobxInstanceCount += 1;\n if (!global.__mobxGlobals.UNCHANGED) {\n global.__mobxGlobals.UNCHANGED = {};\n } // make merge backward compatible\n return global.__mobxGlobals;\n } else {\n global.__mobxInstanceCount = 1;\n return global.__mobxGlobals = /*#__PURE__*/new MobXGlobals();\n }\n}();\nfunction isolateGlobalState() {\n if (globalState.pendingReactions.length || globalState.inBatch || globalState.isRunningReactions) {\n die(36);\n }\n isolateCalled = true;\n if (canMergeGlobalState) {\n var global = getGlobal();\n if (--global.__mobxInstanceCount === 0) {\n global.__mobxGlobals = undefined;\n }\n globalState = new MobXGlobals();\n }\n}\nfunction getGlobalState() {\n return globalState;\n}\n/**\n * For testing purposes only; this will break the internal state of existing observables,\n * but can be used to get back at a stable state after throwing errors\n */\nfunction resetGlobalState() {\n var defaultGlobals = new MobXGlobals();\n for (var key in defaultGlobals) {\n if (persistentKeys.indexOf(key) === -1) {\n globalState[key] = defaultGlobals[key];\n }\n }\n globalState.allowStateChanges = !globalState.enforceActions;\n}\n\nfunction hasObservers(observable) {\n return observable.observers_ && observable.observers_.size > 0;\n}\nfunction getObservers(observable) {\n return observable.observers_;\n}\n// function invariantObservers(observable: IObservable) {\n// const list = observable.observers\n// const map = observable.observersIndexes\n// const l = list.length\n// for (let i = 0; i < l; i++) {\n// const id = list[i].__mapid\n// if (i) {\n// invariant(map[id] === i, \"INTERNAL ERROR maps derivation.__mapid to index in list\") // for performance\n// } else {\n// invariant(!(id in map), \"INTERNAL ERROR observer on index 0 shouldn't be held in map.\") // for performance\n// }\n// }\n// invariant(\n// list.length === 0 || Object.keys(map).length === list.length - 1,\n// \"INTERNAL ERROR there is no junk in map\"\n// )\n// }\nfunction addObserver(observable, node) {\n // invariant(node.dependenciesState !== -1, \"INTERNAL ERROR, can add only dependenciesState !== -1\");\n // invariant(observable._observers.indexOf(node) === -1, \"INTERNAL ERROR add already added node\");\n // invariantObservers(observable);\n observable.observers_.add(node);\n if (observable.lowestObserverState_ > node.dependenciesState_) {\n observable.lowestObserverState_ = node.dependenciesState_;\n }\n // invariantObservers(observable);\n // invariant(observable._observers.indexOf(node) !== -1, \"INTERNAL ERROR didn't add node\");\n}\n\nfunction removeObserver(observable, node) {\n // invariant(globalState.inBatch > 0, \"INTERNAL ERROR, remove should be called only inside batch\");\n // invariant(observable._observers.indexOf(node) !== -1, \"INTERNAL ERROR remove already removed node\");\n // invariantObservers(observable);\n observable.observers_[\"delete\"](node);\n if (observable.observers_.size === 0) {\n // deleting last observer\n queueForUnobservation(observable);\n }\n // invariantObservers(observable);\n // invariant(observable._observers.indexOf(node) === -1, \"INTERNAL ERROR remove already removed node2\");\n}\n\nfunction queueForUnobservation(observable) {\n if (observable.isPendingUnobservation_ === false) {\n // invariant(observable._observers.length === 0, \"INTERNAL ERROR, should only queue for unobservation unobserved observables\");\n observable.isPendingUnobservation_ = true;\n globalState.pendingUnobservations.push(observable);\n }\n}\n/**\n * Batch starts a transaction, at least for purposes of memoizing ComputedValues when nothing else does.\n * During a batch `onBecomeUnobserved` will be called at most once per observable.\n * Avoids unnecessary recalculations.\n */\nfunction startBatch() {\n globalState.inBatch++;\n}\nfunction endBatch() {\n if (--globalState.inBatch === 0) {\n runReactions();\n // the batch is actually about to finish, all unobserving should happen here.\n var list = globalState.pendingUnobservations;\n for (var i = 0; i < list.length; i++) {\n var observable = list[i];\n observable.isPendingUnobservation_ = false;\n if (observable.observers_.size === 0) {\n if (observable.isBeingObserved_) {\n // if this observable had reactive observers, trigger the hooks\n observable.isBeingObserved_ = false;\n observable.onBUO();\n }\n if (observable instanceof ComputedValue) {\n // computed values are automatically teared down when the last observer leaves\n // this process happens recursively, this computed might be the last observabe of another, etc..\n observable.suspend_();\n }\n }\n }\n globalState.pendingUnobservations = [];\n }\n}\nfunction reportObserved(observable) {\n checkIfStateReadsAreAllowed(observable);\n var derivation = globalState.trackingDerivation;\n if (derivation !== null) {\n /**\n * Simple optimization, give each derivation run an unique id (runId)\n * Check if last time this observable was accessed the same runId is used\n * if this is the case, the relation is already known\n */\n if (derivation.runId_ !== observable.lastAccessedBy_) {\n observable.lastAccessedBy_ = derivation.runId_;\n // Tried storing newObserving, or observing, or both as Set, but performance didn't come close...\n derivation.newObserving_[derivation.unboundDepsCount_++] = observable;\n if (!observable.isBeingObserved_ && globalState.trackingContext) {\n observable.isBeingObserved_ = true;\n observable.onBO();\n }\n }\n return observable.isBeingObserved_;\n } else if (observable.observers_.size === 0 && globalState.inBatch > 0) {\n queueForUnobservation(observable);\n }\n return false;\n}\n// function invariantLOS(observable: IObservable, msg: string) {\n// // it's expensive so better not run it in produciton. but temporarily helpful for testing\n// const min = getObservers(observable).reduce((a, b) => Math.min(a, b.dependenciesState), 2)\n// if (min >= observable.lowestObserverState) return // <- the only assumption about `lowestObserverState`\n// throw new Error(\n// \"lowestObserverState is wrong for \" +\n// msg +\n// \" because \" +\n// min +\n// \" < \" +\n// observable.lowestObserverState\n// )\n// }\n/**\n * NOTE: current propagation mechanism will in case of self reruning autoruns behave unexpectedly\n * It will propagate changes to observers from previous run\n * It's hard or maybe impossible (with reasonable perf) to get it right with current approach\n * Hopefully self reruning autoruns aren't a feature people should depend on\n * Also most basic use cases should be ok\n */\n// Called by Atom when its value changes\nfunction propagateChanged(observable) {\n // invariantLOS(observable, \"changed start\");\n if (observable.lowestObserverState_ === IDerivationState_.STALE_) {\n return;\n }\n observable.lowestObserverState_ = IDerivationState_.STALE_;\n // Ideally we use for..of here, but the downcompiled version is really slow...\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n if (process.env.NODE_ENV !== \"production\" && d.isTracing_ !== TraceMode.NONE) {\n logTraceInfo(d, observable);\n }\n d.onBecomeStale_();\n }\n d.dependenciesState_ = IDerivationState_.STALE_;\n });\n // invariantLOS(observable, \"changed end\");\n}\n// Called by ComputedValue when it recalculate and its value changed\nfunction propagateChangeConfirmed(observable) {\n // invariantLOS(observable, \"confirmed start\");\n if (observable.lowestObserverState_ === IDerivationState_.STALE_) {\n return;\n }\n observable.lowestObserverState_ = IDerivationState_.STALE_;\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.POSSIBLY_STALE_) {\n d.dependenciesState_ = IDerivationState_.STALE_;\n if (process.env.NODE_ENV !== \"production\" && d.isTracing_ !== TraceMode.NONE) {\n logTraceInfo(d, observable);\n }\n } else if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_ // this happens during computing of `d`, just keep lowestObserverState up to date.\n ) {\n observable.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n }\n });\n // invariantLOS(observable, \"confirmed end\");\n}\n// Used by computed when its dependency changed, but we don't wan't to immediately recompute.\nfunction propagateMaybeChanged(observable) {\n // invariantLOS(observable, \"maybe start\");\n if (observable.lowestObserverState_ !== IDerivationState_.UP_TO_DATE_) {\n return;\n }\n observable.lowestObserverState_ = IDerivationState_.POSSIBLY_STALE_;\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n d.dependenciesState_ = IDerivationState_.POSSIBLY_STALE_;\n d.onBecomeStale_();\n }\n });\n // invariantLOS(observable, \"maybe end\");\n}\n\nfunction logTraceInfo(derivation, observable) {\n console.log(\"[mobx.trace] '\" + derivation.name_ + \"' is invalidated due to a change in: '\" + observable.name_ + \"'\");\n if (derivation.isTracing_ === TraceMode.BREAK) {\n var lines = [];\n printDepTree(getDependencyTree(derivation), lines, 1);\n // prettier-ignore\n new Function(\"debugger;\\n/*\\nTracing '\" + derivation.name_ + \"'\\n\\nYou are entering this break point because derivation '\" + derivation.name_ + \"' is being traced and '\" + observable.name_ + \"' is now forcing it to update.\\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\\n\\n\" + (derivation instanceof ComputedValue ? derivation.derivation.toString().replace(/[*]\\//g, \"/\") : \"\") + \"\\n\\nThe dependencies for this derivation are:\\n\\n\" + lines.join(\"\\n\") + \"\\n*/\\n \")();\n }\n}\nfunction printDepTree(tree, lines, depth) {\n if (lines.length >= 1000) {\n lines.push(\"(and many more)\");\n return;\n }\n lines.push(\"\" + \"\\t\".repeat(depth - 1) + tree.name);\n if (tree.dependencies) {\n tree.dependencies.forEach(function (child) {\n return printDepTree(child, lines, depth + 1);\n });\n }\n}\n\nvar Reaction = /*#__PURE__*/function () {\n // nodes we are looking at. Our value depends on these nodes\n\n function Reaction(name_, onInvalidate_, errorHandler_, requiresObservable_) {\n if (name_ === void 0) {\n name_ = process.env.NODE_ENV !== \"production\" ? \"Reaction@\" + getNextId() : \"Reaction\";\n }\n this.name_ = void 0;\n this.onInvalidate_ = void 0;\n this.errorHandler_ = void 0;\n this.requiresObservable_ = void 0;\n this.observing_ = [];\n this.newObserving_ = [];\n this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n this.diffValue_ = 0;\n this.runId_ = 0;\n this.unboundDepsCount_ = 0;\n this.isDisposed_ = false;\n this.isScheduled_ = false;\n this.isTrackPending_ = false;\n this.isRunning_ = false;\n this.isTracing_ = TraceMode.NONE;\n this.name_ = name_;\n this.onInvalidate_ = onInvalidate_;\n this.errorHandler_ = errorHandler_;\n this.requiresObservable_ = requiresObservable_;\n }\n var _proto = Reaction.prototype;\n _proto.onBecomeStale_ = function onBecomeStale_() {\n this.schedule_();\n };\n _proto.schedule_ = function schedule_() {\n if (!this.isScheduled_) {\n this.isScheduled_ = true;\n globalState.pendingReactions.push(this);\n runReactions();\n }\n };\n _proto.isScheduled = function isScheduled() {\n return this.isScheduled_;\n }\n /**\n * internal, use schedule() if you intend to kick off a reaction\n */;\n _proto.runReaction_ = function runReaction_() {\n if (!this.isDisposed_) {\n startBatch();\n this.isScheduled_ = false;\n var prev = globalState.trackingContext;\n globalState.trackingContext = this;\n if (shouldCompute(this)) {\n this.isTrackPending_ = true;\n try {\n this.onInvalidate_();\n if (process.env.NODE_ENV !== \"production\" && this.isTrackPending_ && isSpyEnabled()) {\n // onInvalidate didn't trigger track right away..\n spyReport({\n name: this.name_,\n type: \"scheduled-reaction\"\n });\n }\n } catch (e) {\n this.reportExceptionInDerivation_(e);\n }\n }\n globalState.trackingContext = prev;\n endBatch();\n }\n };\n _proto.track = function track(fn) {\n if (this.isDisposed_) {\n return;\n // console.warn(\"Reaction already disposed\") // Note: Not a warning / error in mobx 4 either\n }\n\n startBatch();\n var notify = isSpyEnabled();\n var startTime;\n if (process.env.NODE_ENV !== \"production\" && notify) {\n startTime = Date.now();\n spyReportStart({\n name: this.name_,\n type: \"reaction\"\n });\n }\n this.isRunning_ = true;\n var prevReaction = globalState.trackingContext; // reactions could create reactions...\n globalState.trackingContext = this;\n var result = trackDerivedFunction(this, fn, undefined);\n globalState.trackingContext = prevReaction;\n this.isRunning_ = false;\n this.isTrackPending_ = false;\n if (this.isDisposed_) {\n // disposed during last run. Clean up everything that was bound after the dispose call.\n clearObserving(this);\n }\n if (isCaughtException(result)) {\n this.reportExceptionInDerivation_(result.cause);\n }\n if (process.env.NODE_ENV !== \"production\" && notify) {\n spyReportEnd({\n time: Date.now() - startTime\n });\n }\n endBatch();\n };\n _proto.reportExceptionInDerivation_ = function reportExceptionInDerivation_(error) {\n var _this = this;\n if (this.errorHandler_) {\n this.errorHandler_(error, this);\n return;\n }\n if (globalState.disableErrorBoundaries) {\n throw error;\n }\n var message = process.env.NODE_ENV !== \"production\" ? \"[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '\" + this + \"'\" : \"[mobx] uncaught error in '\" + this + \"'\";\n if (!globalState.suppressReactionErrors) {\n console.error(message, error);\n /** If debugging brought you here, please, read the above message :-). Tnx! */\n } else if (process.env.NODE_ENV !== \"production\") {\n console.warn(\"[mobx] (error in reaction '\" + this.name_ + \"' suppressed, fix error of causing action below)\");\n } // prettier-ignore\n if (process.env.NODE_ENV !== \"production\" && isSpyEnabled()) {\n spyReport({\n type: \"error\",\n name: this.name_,\n message: message,\n error: \"\" + error\n });\n }\n globalState.globalReactionErrorHandlers.forEach(function (f) {\n return f(error, _this);\n });\n };\n _proto.dispose = function dispose() {\n if (!this.isDisposed_) {\n this.isDisposed_ = true;\n if (!this.isRunning_) {\n // if disposed while running, clean up later. Maybe not optimal, but rare case\n startBatch();\n clearObserving(this);\n endBatch();\n }\n }\n };\n _proto.getDisposer_ = function getDisposer_(abortSignal) {\n var _this2 = this;\n var dispose = function dispose() {\n _this2.dispose();\n abortSignal == null ? void 0 : abortSignal.removeEventListener == null ? void 0 : abortSignal.removeEventListener(\"abort\", dispose);\n };\n abortSignal == null ? void 0 : abortSignal.addEventListener == null ? void 0 : abortSignal.addEventListener(\"abort\", dispose);\n dispose[$mobx] = this;\n return dispose;\n };\n _proto.toString = function toString() {\n return \"Reaction[\" + this.name_ + \"]\";\n };\n _proto.trace = function trace$1(enterBreakPoint) {\n if (enterBreakPoint === void 0) {\n enterBreakPoint = false;\n }\n trace(this, enterBreakPoint);\n };\n return Reaction;\n}();\nfunction onReactionError(handler) {\n globalState.globalReactionErrorHandlers.push(handler);\n return function () {\n var idx = globalState.globalReactionErrorHandlers.indexOf(handler);\n if (idx >= 0) {\n globalState.globalReactionErrorHandlers.splice(idx, 1);\n }\n };\n}\n/**\n * Magic number alert!\n * Defines within how many times a reaction is allowed to re-trigger itself\n * until it is assumed that this is gonna be a never ending loop...\n */\nvar MAX_REACTION_ITERATIONS = 100;\nvar reactionScheduler = function reactionScheduler(f) {\n return f();\n};\nfunction runReactions() {\n // Trampolining, if runReactions are already running, new reactions will be picked up\n if (globalState.inBatch > 0 || globalState.isRunningReactions) {\n return;\n }\n reactionScheduler(runReactionsHelper);\n}\nfunction runReactionsHelper() {\n globalState.isRunningReactions = true;\n var allReactions = globalState.pendingReactions;\n var iterations = 0;\n // While running reactions, new reactions might be triggered.\n // Hence we work with two variables and check whether\n // we converge to no remaining reactions after a while.\n while (allReactions.length > 0) {\n if (++iterations === MAX_REACTION_ITERATIONS) {\n console.error(process.env.NODE_ENV !== \"production\" ? \"Reaction doesn't converge to a stable state after \" + MAX_REACTION_ITERATIONS + \" iterations.\" + (\" Probably there is a cycle in the reactive function: \" + allReactions[0]) : \"[mobx] cycle in reaction: \" + allReactions[0]);\n allReactions.splice(0); // clear reactions\n }\n\n var remainingReactions = allReactions.splice(0);\n for (var i = 0, l = remainingReactions.length; i < l; i++) {\n remainingReactions[i].runReaction_();\n }\n }\n globalState.isRunningReactions = false;\n}\nvar isReaction = /*#__PURE__*/createInstanceofPredicate(\"Reaction\", Reaction);\nfunction setReactionScheduler(fn) {\n var baseScheduler = reactionScheduler;\n reactionScheduler = function reactionScheduler(f) {\n return fn(function () {\n return baseScheduler(f);\n });\n };\n}\n\nfunction isSpyEnabled() {\n return process.env.NODE_ENV !== \"production\" && !!globalState.spyListeners.length;\n}\nfunction spyReport(event) {\n if (!(process.env.NODE_ENV !== \"production\")) {\n return;\n } // dead code elimination can do the rest\n if (!globalState.spyListeners.length) {\n return;\n }\n var listeners = globalState.spyListeners;\n for (var i = 0, l = listeners.length; i < l; i++) {\n listeners[i](event);\n }\n}\nfunction spyReportStart(event) {\n if (!(process.env.NODE_ENV !== \"production\")) {\n return;\n }\n var change = _extends({}, event, {\n spyReportStart: true\n });\n spyReport(change);\n}\nvar END_EVENT = {\n type: \"report-end\",\n spyReportEnd: true\n};\nfunction spyReportEnd(change) {\n if (!(process.env.NODE_ENV !== \"production\")) {\n return;\n }\n if (change) {\n spyReport(_extends({}, change, {\n type: \"report-end\",\n spyReportEnd: true\n }));\n } else {\n spyReport(END_EVENT);\n }\n}\nfunction spy(listener) {\n if (!(process.env.NODE_ENV !== \"production\")) {\n console.warn(\"[mobx.spy] Is a no-op in production builds\");\n return function () {};\n } else {\n globalState.spyListeners.push(listener);\n return once(function () {\n globalState.spyListeners = globalState.spyListeners.filter(function (l) {\n return l !== listener;\n });\n });\n }\n}\n\nvar ACTION = \"action\";\nvar ACTION_BOUND = \"action.bound\";\nvar AUTOACTION = \"autoAction\";\nvar AUTOACTION_BOUND = \"autoAction.bound\";\nvar DEFAULT_ACTION_NAME = \"\";\nvar actionAnnotation = /*#__PURE__*/createActionAnnotation(ACTION);\nvar actionBoundAnnotation = /*#__PURE__*/createActionAnnotation(ACTION_BOUND, {\n bound: true\n});\nvar autoActionAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION, {\n autoAction: true\n});\nvar autoActionBoundAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION_BOUND, {\n autoAction: true,\n bound: true\n});\nfunction createActionFactory(autoAction) {\n var res = function action(arg1, arg2) {\n // action(fn() {})\n if (isFunction(arg1)) {\n return createAction(arg1.name || DEFAULT_ACTION_NAME, arg1, autoAction);\n }\n // action(\"name\", fn() {})\n if (isFunction(arg2)) {\n return createAction(arg1, arg2, autoAction);\n }\n // @action (2022.3 Decorators)\n if (is20223Decorator(arg2)) {\n return (autoAction ? autoActionAnnotation : actionAnnotation).decorate_20223_(arg1, arg2);\n }\n // @action\n if (isStringish(arg2)) {\n return storeAnnotation(arg1, arg2, autoAction ? autoActionAnnotation : actionAnnotation);\n }\n // action(\"name\") & @action(\"name\")\n if (isStringish(arg1)) {\n return createDecoratorAnnotation(createActionAnnotation(autoAction ? AUTOACTION : ACTION, {\n name: arg1,\n autoAction: autoAction\n }));\n }\n if (process.env.NODE_ENV !== \"production\") {\n die(\"Invalid arguments for `action`\");\n }\n };\n return res;\n}\nvar action = /*#__PURE__*/createActionFactory(false);\nObject.assign(action, actionAnnotation);\nvar autoAction = /*#__PURE__*/createActionFactory(true);\nObject.assign(autoAction, autoActionAnnotation);\naction.bound = /*#__PURE__*/createDecoratorAnnotation(actionBoundAnnotation);\nautoAction.bound = /*#__PURE__*/createDecoratorAnnotation(autoActionBoundAnnotation);\nfunction runInAction(fn) {\n return executeAction(fn.name || DEFAULT_ACTION_NAME, false, fn, this, undefined);\n}\nfunction isAction(thing) {\n return isFunction(thing) && thing.isMobxAction === true;\n}\n\n/**\n * Creates a named reactive view and keeps it alive, so that the view is always\n * updated if one of the dependencies changes, even when the view is not further used by something else.\n * @param view The reactive view\n * @returns disposer function, which can be used to stop the view from being updated in the future.\n */\nfunction autorun(view, opts) {\n var _opts$name, _opts, _opts2, _opts2$signal, _opts3;\n if (opts === void 0) {\n opts = EMPTY_OBJECT;\n }\n if (process.env.NODE_ENV !== \"production\") {\n if (!isFunction(view)) {\n die(\"Autorun expects a function as first argument\");\n }\n if (isAction(view)) {\n die(\"Autorun does not accept actions since actions are untrackable\");\n }\n }\n var name = (_opts$name = (_opts = opts) == null ? void 0 : _opts.name) != null ? _opts$name : process.env.NODE_ENV !== \"production\" ? view.name || \"Autorun@\" + getNextId() : \"Autorun\";\n var runSync = !opts.scheduler && !opts.delay;\n var reaction;\n if (runSync) {\n // normal autorun\n reaction = new Reaction(name, function () {\n this.track(reactionRunner);\n }, opts.onError, opts.requiresObservable);\n } else {\n var scheduler = createSchedulerFromOptions(opts);\n // debounced autorun\n var isScheduled = false;\n reaction = new Reaction(name, function () {\n if (!isScheduled) {\n isScheduled = true;\n scheduler(function () {\n isScheduled = false;\n if (!reaction.isDisposed_) {\n reaction.track(reactionRunner);\n }\n });\n }\n }, opts.onError, opts.requiresObservable);\n }\n function reactionRunner() {\n view(reaction);\n }\n if (!((_opts2 = opts) != null && (_opts2$signal = _opts2.signal) != null && _opts2$signal.aborted)) {\n reaction.schedule_();\n }\n return reaction.getDisposer_((_opts3 = opts) == null ? void 0 : _opts3.signal);\n}\nvar run = function run(f) {\n return f();\n};\nfunction createSchedulerFromOptions(opts) {\n return opts.scheduler ? opts.scheduler : opts.delay ? function (f) {\n return setTimeout(f, opts.delay);\n } : run;\n}\nfunction reaction(expression, effect, opts) {\n var _opts$name2, _opts4, _opts4$signal, _opts5;\n if (opts === void 0) {\n opts = EMPTY_OBJECT;\n }\n if (process.env.NODE_ENV !== \"production\") {\n if (!isFunction(expression) || !isFunction(effect)) {\n die(\"First and second argument to reaction should be functions\");\n }\n if (!isPlainObject(opts)) {\n die(\"Third argument of reactions should be an object\");\n }\n }\n var name = (_opts$name2 = opts.name) != null ? _opts$name2 : process.env.NODE_ENV !== \"production\" ? \"Reaction@\" + getNextId() : \"Reaction\";\n var effectAction = action(name, opts.onError ? wrapErrorHandler(opts.onError, effect) : effect);\n var runSync = !opts.scheduler && !opts.delay;\n var scheduler = createSchedulerFromOptions(opts);\n var firstTime = true;\n var isScheduled = false;\n var value;\n var oldValue;\n var equals = opts.compareStructural ? comparer.structural : opts.equals || comparer[\"default\"];\n var r = new Reaction(name, function () {\n if (firstTime || runSync) {\n reactionRunner();\n } else if (!isScheduled) {\n isScheduled = true;\n scheduler(reactionRunner);\n }\n }, opts.onError, opts.requiresObservable);\n function reactionRunner() {\n isScheduled = false;\n if (r.isDisposed_) {\n return;\n }\n var changed = false;\n r.track(function () {\n var nextValue = allowStateChanges(false, function () {\n return expression(r);\n });\n changed = firstTime || !equals(value, nextValue);\n oldValue = value;\n value = nextValue;\n });\n if (firstTime && opts.fireImmediately) {\n effectAction(value, oldValue, r);\n } else if (!firstTime && changed) {\n effectAction(value, oldValue, r);\n }\n firstTime = false;\n }\n if (!((_opts4 = opts) != null && (_opts4$signal = _opts4.signal) != null && _opts4$signal.aborted)) {\n r.schedule_();\n }\n return r.getDisposer_((_opts5 = opts) == null ? void 0 : _opts5.signal);\n}\nfunction wrapErrorHandler(errorHandler, baseFn) {\n return function () {\n try {\n return baseFn.apply(this, arguments);\n } catch (e) {\n errorHandler.call(this, e);\n }\n };\n}\n\nvar ON_BECOME_OBSERVED = \"onBO\";\nvar ON_BECOME_UNOBSERVED = \"onBUO\";\nfunction onBecomeObserved(thing, arg2, arg3) {\n return interceptHook(ON_BECOME_OBSERVED, thing, arg2, arg3);\n}\nfunction onBecomeUnobserved(thing, arg2, arg3) {\n return interceptHook(ON_BECOME_UNOBSERVED, thing, arg2, arg3);\n}\nfunction interceptHook(hook, thing, arg2, arg3) {\n var atom = typeof arg3 === \"function\" ? getAtom(thing, arg2) : getAtom(thing);\n var cb = isFunction(arg3) ? arg3 : arg2;\n var listenersKey = hook + \"L\";\n if (atom[listenersKey]) {\n atom[listenersKey].add(cb);\n } else {\n atom[listenersKey] = new Set([cb]);\n }\n return function () {\n var hookListeners = atom[listenersKey];\n if (hookListeners) {\n hookListeners[\"delete\"](cb);\n if (hookListeners.size === 0) {\n delete atom[listenersKey];\n }\n }\n };\n}\n\nvar NEVER = \"never\";\nvar ALWAYS = \"always\";\nvar OBSERVED = \"observed\";\n// const IF_AVAILABLE = \"ifavailable\"\nfunction configure(options) {\n if (options.isolateGlobalState === true) {\n isolateGlobalState();\n }\n var useProxies = options.useProxies,\n enforceActions = options.enforceActions;\n if (useProxies !== undefined) {\n globalState.useProxies = useProxies === ALWAYS ? true : useProxies === NEVER ? false : typeof Proxy !== \"undefined\";\n }\n if (useProxies === \"ifavailable\") {\n globalState.verifyProxies = true;\n }\n if (enforceActions !== undefined) {\n var ea = enforceActions === ALWAYS ? ALWAYS : enforceActions === OBSERVED;\n globalState.enforceActions = ea;\n globalState.allowStateChanges = ea === true || ea === ALWAYS ? false : true;\n }\n [\"computedRequiresReaction\", \"reactionRequiresObservable\", \"observableRequiresReaction\", \"disableErrorBoundaries\", \"safeDescriptors\"].forEach(function (key) {\n if (key in options) {\n globalState[key] = !!options[key];\n }\n });\n globalState.allowStateReads = !globalState.observableRequiresReaction;\n if (process.env.NODE_ENV !== \"production\" && globalState.disableErrorBoundaries === true) {\n console.warn(\"WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled.\");\n }\n if (options.reactionScheduler) {\n setReactionScheduler(options.reactionScheduler);\n }\n}\n\nfunction extendObservable(target, properties, annotations, options) {\n if (process.env.NODE_ENV !== \"production\") {\n if (arguments.length > 4) {\n die(\"'extendObservable' expected 2-4 arguments\");\n }\n if (typeof target !== \"object\") {\n die(\"'extendObservable' expects an object as first argument\");\n }\n if (isObservableMap(target)) {\n die(\"'extendObservable' should not be used on maps, use map.merge instead\");\n }\n if (!isPlainObject(properties)) {\n die(\"'extendObservable' only accepts plain objects as second argument\");\n }\n if (isObservable(properties) || isObservable(annotations)) {\n die(\"Extending an object with another observable (object) is not supported\");\n }\n }\n // Pull descriptors first, so we don't have to deal with props added by administration ($mobx)\n var descriptors = getOwnPropertyDescriptors(properties);\n initObservable(function () {\n var adm = asObservableObject(target, options)[$mobx];\n ownKeys(descriptors).forEach(function (key) {\n adm.extend_(key, descriptors[key],\n // must pass \"undefined\" for { key: undefined }\n !annotations ? true : key in annotations ? annotations[key] : true);\n });\n });\n return target;\n}\n\nfunction getDependencyTree(thing, property) {\n return nodeToDependencyTree(getAtom(thing, property));\n}\nfunction nodeToDependencyTree(node) {\n var result = {\n name: node.name_\n };\n if (node.observing_ && node.observing_.length > 0) {\n result.dependencies = unique(node.observing_).map(nodeToDependencyTree);\n }\n return result;\n}\nfunction getObserverTree(thing, property) {\n return nodeToObserverTree(getAtom(thing, property));\n}\nfunction nodeToObserverTree(node) {\n var result = {\n name: node.name_\n };\n if (hasObservers(node)) {\n result.observers = Array.from(getObservers(node)).map(nodeToObserverTree);\n }\n return result;\n}\nfunction unique(list) {\n return Array.from(new Set(list));\n}\n\nvar generatorId = 0;\nfunction FlowCancellationError() {\n this.message = \"FLOW_CANCELLED\";\n}\nFlowCancellationError.prototype = /*#__PURE__*/Object.create(Error.prototype);\nfunction isFlowCancellationError(error) {\n return error instanceof FlowCancellationError;\n}\nvar flowAnnotation = /*#__PURE__*/createFlowAnnotation(\"flow\");\nvar flowBoundAnnotation = /*#__PURE__*/createFlowAnnotation(\"flow.bound\", {\n bound: true\n});\nvar flow = /*#__PURE__*/Object.assign(function flow(arg1, arg2) {\n // @flow (2022.3 Decorators)\n if (is20223Decorator(arg2)) {\n return flowAnnotation.decorate_20223_(arg1, arg2);\n }\n // @flow\n if (isStringish(arg2)) {\n return storeAnnotation(arg1, arg2, flowAnnotation);\n }\n // flow(fn)\n if (process.env.NODE_ENV !== \"production\" && arguments.length !== 1) {\n die(\"Flow expects single argument with generator function\");\n }\n var generator = arg1;\n var name = generator.name || \"\";\n // Implementation based on https://github.com/tj/co/blob/master/index.js\n var res = function res() {\n var ctx = this;\n var args = arguments;\n var runId = ++generatorId;\n var gen = action(name + \" - runid: \" + runId + \" - init\", generator).apply(ctx, args);\n var rejector;\n var pendingPromise = undefined;\n var promise = new Promise(function (resolve, reject) {\n var stepId = 0;\n rejector = reject;\n function onFulfilled(res) {\n pendingPromise = undefined;\n var ret;\n try {\n ret = action(name + \" - runid: \" + runId + \" - yield \" + stepId++, gen.next).call(gen, res);\n } catch (e) {\n return reject(e);\n }\n next(ret);\n }\n function onRejected(err) {\n pendingPromise = undefined;\n var ret;\n try {\n ret = action(name + \" - runid: \" + runId + \" - yield \" + stepId++, gen[\"throw\"]).call(gen, err);\n } catch (e) {\n return reject(e);\n }\n next(ret);\n }\n function next(ret) {\n if (isFunction(ret == null ? void 0 : ret.then)) {\n // an async iterator\n ret.then(next, reject);\n return;\n }\n if (ret.done) {\n return resolve(ret.value);\n }\n pendingPromise = Promise.resolve(ret.value);\n return pendingPromise.then(onFulfilled, onRejected);\n }\n onFulfilled(undefined); // kick off the process\n });\n\n promise.cancel = action(name + \" - runid: \" + runId + \" - cancel\", function () {\n try {\n if (pendingPromise) {\n cancelPromise(pendingPromise);\n }\n // Finally block can return (or yield) stuff..\n var _res = gen[\"return\"](undefined);\n // eat anything that promise would do, it's cancelled!\n var yieldedPromise = Promise.resolve(_res.value);\n yieldedPromise.then(noop, noop);\n cancelPromise(yieldedPromise); // maybe it can be cancelled :)\n // reject our original promise\n rejector(new FlowCancellationError());\n } catch (e) {\n rejector(e); // there could be a throwing finally block\n }\n });\n\n return promise;\n };\n res.isMobXFlow = true;\n return res;\n}, flowAnnotation);\nflow.bound = /*#__PURE__*/createDecoratorAnnotation(flowBoundAnnotation);\nfunction cancelPromise(promise) {\n if (isFunction(promise.cancel)) {\n promise.cancel();\n }\n}\nfunction flowResult(result) {\n return result; // just tricking TypeScript :)\n}\n\nfunction isFlow(fn) {\n return (fn == null ? void 0 : fn.isMobXFlow) === true;\n}\n\nfunction interceptReads(thing, propOrHandler, handler) {\n var target;\n if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) {\n target = getAdministration(thing);\n } else if (isObservableObject(thing)) {\n if (process.env.NODE_ENV !== \"production\" && !isStringish(propOrHandler)) {\n return die(\"InterceptReads can only be used with a specific property, not with an object in general\");\n }\n target = getAdministration(thing, propOrHandler);\n } else if (process.env.NODE_ENV !== \"production\") {\n return die(\"Expected observable map, object or array as first array\");\n }\n if (process.env.NODE_ENV !== \"production\" && target.dehancer !== undefined) {\n return die(\"An intercept reader was already established\");\n }\n target.dehancer = typeof propOrHandler === \"function\" ? propOrHandler : handler;\n return function () {\n target.dehancer = undefined;\n };\n}\n\nfunction intercept(thing, propOrHandler, handler) {\n if (isFunction(handler)) {\n return interceptProperty(thing, propOrHandler, handler);\n } else {\n return interceptInterceptable(thing, propOrHandler);\n }\n}\nfunction interceptInterceptable(thing, handler) {\n return getAdministration(thing).intercept_(handler);\n}\nfunction interceptProperty(thing, property, handler) {\n return getAdministration(thing, property).intercept_(handler);\n}\n\nfunction _isComputed(value, property) {\n if (property === undefined) {\n return isComputedValue(value);\n }\n if (isObservableObject(value) === false) {\n return false;\n }\n if (!value[$mobx].values_.has(property)) {\n return false;\n }\n var atom = getAtom(value, property);\n return isComputedValue(atom);\n}\nfunction isComputed(value) {\n if (process.env.NODE_ENV !== \"production\" && arguments.length > 1) {\n return die(\"isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property\");\n }\n return _isComputed(value);\n}\nfunction isComputedProp(value, propName) {\n if (process.env.NODE_ENV !== \"production\" && !isStringish(propName)) {\n return die(\"isComputed expected a property name as second argument\");\n }\n return _isComputed(value, propName);\n}\n\nfunction _isObservable(value, property) {\n if (!value) {\n return false;\n }\n if (property !== undefined) {\n if (process.env.NODE_ENV !== \"production\" && (isObservableMap(value) || isObservableArray(value))) {\n return die(\"isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.\");\n }\n if (isObservableObject(value)) {\n return value[$mobx].values_.has(property);\n }\n return false;\n }\n // For first check, see #701\n return isObservableObject(value) || !!value[$mobx] || isAtom(value) || isReaction(value) || isComputedValue(value);\n}\nfunction isObservable(value) {\n if (process.env.NODE_ENV !== \"production\" && arguments.length !== 1) {\n die(\"isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property\");\n }\n return _isObservable(value);\n}\nfunction isObservableProp(value, propName) {\n if (process.env.NODE_ENV !== \"production\" && !isStringish(propName)) {\n return die(\"expected a property name as second argument\");\n }\n return _isObservable(value, propName);\n}\n\nfunction keys(obj) {\n if (isObservableObject(obj)) {\n return obj[$mobx].keys_();\n }\n if (isObservableMap(obj) || isObservableSet(obj)) {\n return Array.from(obj.keys());\n }\n if (isObservableArray(obj)) {\n return obj.map(function (_, index) {\n return index;\n });\n }\n die(5);\n}\nfunction values(obj) {\n if (isObservableObject(obj)) {\n return keys(obj).map(function (key) {\n return obj[key];\n });\n }\n if (isObservableMap(obj)) {\n return keys(obj).map(function (key) {\n return obj.get(key);\n });\n }\n if (isObservableSet(obj)) {\n return Array.from(obj.values());\n }\n if (isObservableArray(obj)) {\n return obj.slice();\n }\n die(6);\n}\nfunction entries(obj) {\n if (isObservableObject(obj)) {\n return keys(obj).map(function (key) {\n return [key, obj[key]];\n });\n }\n if (isObservableMap(obj)) {\n return keys(obj).map(function (key) {\n return [key, obj.get(key)];\n });\n }\n if (isObservableSet(obj)) {\n return Array.from(obj.entries());\n }\n if (isObservableArray(obj)) {\n return obj.map(function (key, index) {\n return [index, key];\n });\n }\n die(7);\n}\nfunction set(obj, key, value) {\n if (arguments.length === 2 && !isObservableSet(obj)) {\n startBatch();\n var _values = key;\n try {\n for (var _key in _values) {\n set(obj, _key, _values[_key]);\n }\n } finally {\n endBatch();\n }\n return;\n }\n if (isObservableObject(obj)) {\n obj[$mobx].set_(key, value);\n } else if (isObservableMap(obj)) {\n obj.set(key, value);\n } else if (isObservableSet(obj)) {\n obj.add(key);\n } else if (isObservableArray(obj)) {\n if (typeof key !== \"number\") {\n key = parseInt(key, 10);\n }\n if (key < 0) {\n die(\"Invalid index: '\" + key + \"'\");\n }\n startBatch();\n if (key >= obj.length) {\n obj.length = key + 1;\n }\n obj[key] = value;\n endBatch();\n } else {\n die(8);\n }\n}\nfunction remove(obj, key) {\n if (isObservableObject(obj)) {\n obj[$mobx].delete_(key);\n } else if (isObservableMap(obj)) {\n obj[\"delete\"](key);\n } else if (isObservableSet(obj)) {\n obj[\"delete\"](key);\n } else if (isObservableArray(obj)) {\n if (typeof key !== \"number\") {\n key = parseInt(key, 10);\n }\n obj.splice(key, 1);\n } else {\n die(9);\n }\n}\nfunction has(obj, key) {\n if (isObservableObject(obj)) {\n return obj[$mobx].has_(key);\n } else if (isObservableMap(obj)) {\n return obj.has(key);\n } else if (isObservableSet(obj)) {\n return obj.has(key);\n } else if (isObservableArray(obj)) {\n return key >= 0 && key < obj.length;\n }\n die(10);\n}\nfunction get(obj, key) {\n if (!has(obj, key)) {\n return undefined;\n }\n if (isObservableObject(obj)) {\n return obj[$mobx].get_(key);\n } else if (isObservableMap(obj)) {\n return obj.get(key);\n } else if (isObservableArray(obj)) {\n return obj[key];\n }\n die(11);\n}\nfunction apiDefineProperty(obj, key, descriptor) {\n if (isObservableObject(obj)) {\n return obj[$mobx].defineProperty_(key, descriptor);\n }\n die(39);\n}\nfunction apiOwnKeys(obj) {\n if (isObservableObject(obj)) {\n return obj[$mobx].ownKeys_();\n }\n die(38);\n}\n\nfunction observe(thing, propOrCb, cbOrFire, fireImmediately) {\n if (isFunction(cbOrFire)) {\n return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately);\n } else {\n return observeObservable(thing, propOrCb, cbOrFire);\n }\n}\nfunction observeObservable(thing, listener, fireImmediately) {\n return getAdministration(thing).observe_(listener, fireImmediately);\n}\nfunction observeObservableProperty(thing, property, listener, fireImmediately) {\n return getAdministration(thing, property).observe_(listener, fireImmediately);\n}\n\nfunction cache(map, key, value) {\n map.set(key, value);\n return value;\n}\nfunction toJSHelper(source, __alreadySeen) {\n if (source == null || typeof source !== \"object\" || source instanceof Date || !isObservable(source)) {\n return source;\n }\n if (isObservableValue(source) || isComputedValue(source)) {\n return toJSHelper(source.get(), __alreadySeen);\n }\n if (__alreadySeen.has(source)) {\n return __alreadySeen.get(source);\n }\n if (isObservableArray(source)) {\n var res = cache(__alreadySeen, source, new Array(source.length));\n source.forEach(function (value, idx) {\n res[idx] = toJSHelper(value, __alreadySeen);\n });\n return res;\n }\n if (isObservableSet(source)) {\n var _res = cache(__alreadySeen, source, new Set());\n source.forEach(function (value) {\n _res.add(toJSHelper(value, __alreadySeen));\n });\n return _res;\n }\n if (isObservableMap(source)) {\n var _res2 = cache(__alreadySeen, source, new Map());\n source.forEach(function (value, key) {\n _res2.set(key, toJSHelper(value, __alreadySeen));\n });\n return _res2;\n } else {\n // must be observable object\n var _res3 = cache(__alreadySeen, source, {});\n apiOwnKeys(source).forEach(function (key) {\n if (objectPrototype.propertyIsEnumerable.call(source, key)) {\n _res3[key] = toJSHelper(source[key], __alreadySeen);\n }\n });\n return _res3;\n }\n}\n/**\n * Recursively converts an observable to it's non-observable native counterpart.\n * It does NOT recurse into non-observables, these are left as they are, even if they contain observables.\n * Computed and other non-enumerable properties are completely ignored.\n * Complex scenarios require custom solution, eg implementing `toJSON` or using `serializr` lib.\n */\nfunction toJS(source, options) {\n if (process.env.NODE_ENV !== \"production\" && options) {\n die(\"toJS no longer supports options\");\n }\n return toJSHelper(source, new Map());\n}\n\nfunction trace() {\n if (!(process.env.NODE_ENV !== \"production\")) {\n return;\n }\n var enterBreakPoint = false;\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n if (typeof args[args.length - 1] === \"boolean\") {\n enterBreakPoint = args.pop();\n }\n var derivation = getAtomFromArgs(args);\n if (!derivation) {\n return die(\"'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly\");\n }\n if (derivation.isTracing_ === TraceMode.NONE) {\n console.log(\"[mobx.trace] '\" + derivation.name_ + \"' tracing enabled\");\n }\n derivation.isTracing_ = enterBreakPoint ? TraceMode.BREAK : TraceMode.LOG;\n}\nfunction getAtomFromArgs(args) {\n switch (args.length) {\n case 0:\n return globalState.trackingDerivation;\n case 1:\n return getAtom(args[0]);\n case 2:\n return getAtom(args[0], args[1]);\n }\n}\n\n/**\n * During a transaction no views are updated until the end of the transaction.\n * The transaction will be run synchronously nonetheless.\n *\n * @param action a function that updates some reactive state\n * @returns any value that was returned by the 'action' parameter.\n */\nfunction transaction(action, thisArg) {\n if (thisArg === void 0) {\n thisArg = undefined;\n }\n startBatch();\n try {\n return action.apply(thisArg);\n } finally {\n endBatch();\n }\n}\n\nfunction when(predicate, arg1, arg2) {\n if (arguments.length === 1 || arg1 && typeof arg1 === \"object\") {\n return whenPromise(predicate, arg1);\n }\n return _when(predicate, arg1, arg2 || {});\n}\nfunction _when(predicate, effect, opts) {\n var timeoutHandle;\n if (typeof opts.timeout === \"number\") {\n var error = new Error(\"WHEN_TIMEOUT\");\n timeoutHandle = setTimeout(function () {\n if (!disposer[$mobx].isDisposed_) {\n disposer();\n if (opts.onError) {\n opts.onError(error);\n } else {\n throw error;\n }\n }\n }, opts.timeout);\n }\n opts.name = process.env.NODE_ENV !== \"production\" ? opts.name || \"When@\" + getNextId() : \"When\";\n var effectAction = createAction(process.env.NODE_ENV !== \"production\" ? opts.name + \"-effect\" : \"When-effect\", effect);\n // eslint-disable-next-line\n var disposer = autorun(function (r) {\n // predicate should not change state\n var cond = allowStateChanges(false, predicate);\n if (cond) {\n r.dispose();\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n }\n effectAction();\n }\n }, opts);\n return disposer;\n}\nfunction whenPromise(predicate, opts) {\n var _opts$signal;\n if (process.env.NODE_ENV !== \"production\" && opts && opts.onError) {\n return die(\"the options 'onError' and 'promise' cannot be combined\");\n }\n if (opts != null && (_opts$signal = opts.signal) != null && _opts$signal.aborted) {\n return Object.assign(Promise.reject(new Error(\"WHEN_ABORTED\")), {\n cancel: function cancel() {\n return null;\n }\n });\n }\n var cancel;\n var abort;\n var res = new Promise(function (resolve, reject) {\n var _opts$signal2;\n var disposer = _when(predicate, resolve, _extends({}, opts, {\n onError: reject\n }));\n cancel = function cancel() {\n disposer();\n reject(new Error(\"WHEN_CANCELLED\"));\n };\n abort = function abort() {\n disposer();\n reject(new Error(\"WHEN_ABORTED\"));\n };\n opts == null ? void 0 : (_opts$signal2 = opts.signal) == null ? void 0 : _opts$signal2.addEventListener == null ? void 0 : _opts$signal2.addEventListener(\"abort\", abort);\n })[\"finally\"](function () {\n var _opts$signal3;\n return opts == null ? void 0 : (_opts$signal3 = opts.signal) == null ? void 0 : _opts$signal3.removeEventListener == null ? void 0 : _opts$signal3.removeEventListener(\"abort\", abort);\n });\n res.cancel = cancel;\n return res;\n}\n\nfunction getAdm(target) {\n return target[$mobx];\n}\n// Optimization: we don't need the intermediate objects and could have a completely custom administration for DynamicObjects,\n// and skip either the internal values map, or the base object with its property descriptors!\nvar objectProxyTraps = {\n has: function has(target, name) {\n if (process.env.NODE_ENV !== \"production\" && globalState.trackingDerivation) {\n warnAboutProxyRequirement(\"detect new properties using the 'in' operator. Use 'has' from 'mobx' instead.\");\n }\n return getAdm(target).has_(name);\n },\n get: function get(target, name) {\n return getAdm(target).get_(name);\n },\n set: function set(target, name, value) {\n var _getAdm$set_;\n if (!isStringish(name)) {\n return false;\n }\n if (process.env.NODE_ENV !== \"production\" && !getAdm(target).values_.has(name)) {\n warnAboutProxyRequirement(\"add a new observable property through direct assignment. Use 'set' from 'mobx' instead.\");\n }\n // null (intercepted) -> true (success)\n return (_getAdm$set_ = getAdm(target).set_(name, value, true)) != null ? _getAdm$set_ : true;\n },\n deleteProperty: function deleteProperty(target, name) {\n var _getAdm$delete_;\n if (process.env.NODE_ENV !== \"production\") {\n warnAboutProxyRequirement(\"delete properties from an observable object. Use 'remove' from 'mobx' instead.\");\n }\n if (!isStringish(name)) {\n return false;\n }\n // null (intercepted) -> true (success)\n return (_getAdm$delete_ = getAdm(target).delete_(name, true)) != null ? _getAdm$delete_ : true;\n },\n defineProperty: function defineProperty(target, name, descriptor) {\n var _getAdm$definePropert;\n if (process.env.NODE_ENV !== \"production\") {\n warnAboutProxyRequirement(\"define property on an observable object. Use 'defineProperty' from 'mobx' instead.\");\n }\n // null (intercepted) -> true (success)\n return (_getAdm$definePropert = getAdm(target).defineProperty_(name, descriptor)) != null ? _getAdm$definePropert : true;\n },\n ownKeys: function ownKeys(target) {\n if (process.env.NODE_ENV !== \"production\" && globalState.trackingDerivation) {\n warnAboutProxyRequirement(\"iterate keys to detect added / removed properties. Use 'keys' from 'mobx' instead.\");\n }\n return getAdm(target).ownKeys_();\n },\n preventExtensions: function preventExtensions(target) {\n die(13);\n }\n};\nfunction asDynamicObservableObject(target, options) {\n var _target$$mobx, _target$$mobx$proxy_;\n assertProxies();\n target = asObservableObject(target, options);\n return (_target$$mobx$proxy_ = (_target$$mobx = target[$mobx]).proxy_) != null ? _target$$mobx$proxy_ : _target$$mobx.proxy_ = new Proxy(target, objectProxyTraps);\n}\n\nfunction hasInterceptors(interceptable) {\n return interceptable.interceptors_ !== undefined && interceptable.interceptors_.length > 0;\n}\nfunction registerInterceptor(interceptable, handler) {\n var interceptors = interceptable.interceptors_ || (interceptable.interceptors_ = []);\n interceptors.push(handler);\n return once(function () {\n var idx = interceptors.indexOf(handler);\n if (idx !== -1) {\n interceptors.splice(idx, 1);\n }\n });\n}\nfunction interceptChange(interceptable, change) {\n var prevU = untrackedStart();\n try {\n // Interceptor can modify the array, copy it to avoid concurrent modification, see #1950\n var interceptors = [].concat(interceptable.interceptors_ || []);\n for (var i = 0, l = interceptors.length; i < l; i++) {\n change = interceptors[i](change);\n if (change && !change.type) {\n die(14);\n }\n if (!change) {\n break;\n }\n }\n return change;\n } finally {\n untrackedEnd(prevU);\n }\n}\n\nfunction hasListeners(listenable) {\n return listenable.changeListeners_ !== undefined && listenable.changeListeners_.length > 0;\n}\nfunction registerListener(listenable, handler) {\n var listeners = listenable.changeListeners_ || (listenable.changeListeners_ = []);\n listeners.push(handler);\n return once(function () {\n var idx = listeners.indexOf(handler);\n if (idx !== -1) {\n listeners.splice(idx, 1);\n }\n });\n}\nfunction notifyListeners(listenable, change) {\n var prevU = untrackedStart();\n var listeners = listenable.changeListeners_;\n if (!listeners) {\n return;\n }\n listeners = listeners.slice();\n for (var i = 0, l = listeners.length; i < l; i++) {\n listeners[i](change);\n }\n untrackedEnd(prevU);\n}\n\nfunction makeObservable(target, annotations, options) {\n initObservable(function () {\n var _annotations;\n var adm = asObservableObject(target, options)[$mobx];\n if (process.env.NODE_ENV !== \"production\" && annotations && target[storedAnnotationsSymbol]) {\n die(\"makeObservable second arg must be nullish when using decorators. Mixing @decorator syntax with annotations is not supported.\");\n }\n // Default to decorators\n (_annotations = annotations) != null ? _annotations : annotations = collectStoredAnnotations(target);\n // Annotate\n ownKeys(annotations).forEach(function (key) {\n return adm.make_(key, annotations[key]);\n });\n });\n return target;\n}\n// proto[keysSymbol] = new Set()\nvar keysSymbol = /*#__PURE__*/Symbol(\"mobx-keys\");\nfunction makeAutoObservable(target, overrides, options) {\n if (process.env.NODE_ENV !== \"production\") {\n if (!isPlainObject(target) && !isPlainObject(Object.getPrototypeOf(target))) {\n die(\"'makeAutoObservable' can only be used for classes that don't have a superclass\");\n }\n if (isObservableObject(target)) {\n die(\"makeAutoObservable can only be used on objects not already made observable\");\n }\n }\n // Optimization: avoid visiting protos\n // Assumes that annotation.make_/.extend_ works the same for plain objects\n if (isPlainObject(target)) {\n return extendObservable(target, target, overrides, options);\n }\n initObservable(function () {\n var adm = asObservableObject(target, options)[$mobx];\n // Optimization: cache keys on proto\n // Assumes makeAutoObservable can be called only once per object and can't be used in subclass\n if (!target[keysSymbol]) {\n var proto = Object.getPrototypeOf(target);\n var keys = new Set([].concat(ownKeys(target), ownKeys(proto)));\n keys[\"delete\"](\"constructor\");\n keys[\"delete\"]($mobx);\n addHiddenProp(proto, keysSymbol, keys);\n }\n target[keysSymbol].forEach(function (key) {\n return adm.make_(key,\n // must pass \"undefined\" for { key: undefined }\n !overrides ? true : key in overrides ? overrides[key] : true);\n });\n });\n return target;\n}\n\nvar SPLICE = \"splice\";\nvar UPDATE = \"update\";\nvar MAX_SPLICE_SIZE = 10000; // See e.g. https://github.com/mobxjs/mobx/issues/859\nvar arrayTraps = {\n get: function get(target, name) {\n var adm = target[$mobx];\n if (name === $mobx) {\n return adm;\n }\n if (name === \"length\") {\n return adm.getArrayLength_();\n }\n if (typeof name === \"string\" && !isNaN(name)) {\n return adm.get_(parseInt(name));\n }\n if (hasProp(arrayExtensions, name)) {\n return arrayExtensions[name];\n }\n return target[name];\n },\n set: function set(target, name, value) {\n var adm = target[$mobx];\n if (name === \"length\") {\n adm.setArrayLength_(value);\n }\n if (typeof name === \"symbol\" || isNaN(name)) {\n target[name] = value;\n } else {\n // numeric string\n adm.set_(parseInt(name), value);\n }\n return true;\n },\n preventExtensions: function preventExtensions() {\n die(15);\n }\n};\nvar ObservableArrayAdministration = /*#__PURE__*/function () {\n // this is the prop that gets proxied, so can't replace it!\n\n function ObservableArrayAdministration(name, enhancer, owned_, legacyMode_) {\n if (name === void 0) {\n name = process.env.NODE_ENV !== \"production\" ? \"ObservableArray@\" + getNextId() : \"ObservableArray\";\n }\n this.owned_ = void 0;\n this.legacyMode_ = void 0;\n this.atom_ = void 0;\n this.values_ = [];\n this.interceptors_ = void 0;\n this.changeListeners_ = void 0;\n this.enhancer_ = void 0;\n this.dehancer = void 0;\n this.proxy_ = void 0;\n this.lastKnownLength_ = 0;\n this.owned_ = owned_;\n this.legacyMode_ = legacyMode_;\n this.atom_ = new Atom(name);\n this.enhancer_ = function (newV, oldV) {\n return enhancer(newV, oldV, process.env.NODE_ENV !== \"production\" ? name + \"[..]\" : \"ObservableArray[..]\");\n };\n }\n var _proto = ObservableArrayAdministration.prototype;\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n return value;\n };\n _proto.dehanceValues_ = function dehanceValues_(values) {\n if (this.dehancer !== undefined && values.length > 0) {\n return values.map(this.dehancer);\n }\n return values;\n };\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (fireImmediately === void 0) {\n fireImmediately = false;\n }\n if (fireImmediately) {\n listener({\n observableKind: \"array\",\n object: this.proxy_,\n debugObjectName: this.atom_.name_,\n type: \"splice\",\n index: 0,\n added: this.values_.slice(),\n addedCount: this.values_.length,\n removed: [],\n removedCount: 0\n });\n }\n return registerListener(this, listener);\n };\n _proto.getArrayLength_ = function getArrayLength_() {\n this.atom_.reportObserved();\n return this.values_.length;\n };\n _proto.setArrayLength_ = function setArrayLength_(newLength) {\n if (typeof newLength !== \"number\" || isNaN(newLength) || newLength < 0) {\n die(\"Out of range: \" + newLength);\n }\n var currentLength = this.values_.length;\n if (newLength === currentLength) {\n return;\n } else if (newLength > currentLength) {\n var newItems = new Array(newLength - currentLength);\n for (var i = 0; i < newLength - currentLength; i++) {\n newItems[i] = undefined;\n } // No Array.fill everywhere...\n this.spliceWithArray_(currentLength, 0, newItems);\n } else {\n this.spliceWithArray_(newLength, currentLength - newLength);\n }\n };\n _proto.updateArrayLength_ = function updateArrayLength_(oldLength, delta) {\n if (oldLength !== this.lastKnownLength_) {\n die(16);\n }\n this.lastKnownLength_ += delta;\n if (this.legacyMode_ && delta > 0) {\n reserveArrayBuffer(oldLength + delta + 1);\n }\n };\n _proto.spliceWithArray_ = function spliceWithArray_(index, deleteCount, newItems) {\n var _this = this;\n checkIfStateModificationsAreAllowed(this.atom_);\n var length = this.values_.length;\n if (index === undefined) {\n index = 0;\n } else if (index > length) {\n index = length;\n } else if (index < 0) {\n index = Math.max(0, length + index);\n }\n if (arguments.length === 1) {\n deleteCount = length - index;\n } else if (deleteCount === undefined || deleteCount === null) {\n deleteCount = 0;\n } else {\n deleteCount = Math.max(0, Math.min(deleteCount, length - index));\n }\n if (newItems === undefined) {\n newItems = EMPTY_ARRAY;\n }\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_,\n type: SPLICE,\n index: index,\n removedCount: deleteCount,\n added: newItems\n });\n if (!change) {\n return EMPTY_ARRAY;\n }\n deleteCount = change.removedCount;\n newItems = change.added;\n }\n newItems = newItems.length === 0 ? newItems : newItems.map(function (v) {\n return _this.enhancer_(v, undefined);\n });\n if (this.legacyMode_ || process.env.NODE_ENV !== \"production\") {\n var lengthDelta = newItems.length - deleteCount;\n this.updateArrayLength_(length, lengthDelta); // checks if internal array wasn't modified\n }\n\n var res = this.spliceItemsIntoValues_(index, deleteCount, newItems);\n if (deleteCount !== 0 || newItems.length !== 0) {\n this.notifyArraySplice_(index, newItems, res);\n }\n return this.dehanceValues_(res);\n };\n _proto.spliceItemsIntoValues_ = function spliceItemsIntoValues_(index, deleteCount, newItems) {\n if (newItems.length < MAX_SPLICE_SIZE) {\n var _this$values_;\n return (_this$values_ = this.values_).splice.apply(_this$values_, [index, deleteCount].concat(newItems));\n } else {\n // The items removed by the splice\n var res = this.values_.slice(index, index + deleteCount);\n // The items that that should remain at the end of the array\n var oldItems = this.values_.slice(index + deleteCount);\n // New length is the previous length + addition count - deletion count\n this.values_.length += newItems.length - deleteCount;\n for (var i = 0; i < newItems.length; i++) {\n this.values_[index + i] = newItems[i];\n }\n for (var _i = 0; _i < oldItems.length; _i++) {\n this.values_[index + newItems.length + _i] = oldItems[_i];\n }\n return res;\n }\n };\n _proto.notifyArrayChildUpdate_ = function notifyArrayChildUpdate_(index, newValue, oldValue) {\n var notifySpy = !this.owned_ && isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"array\",\n object: this.proxy_,\n type: UPDATE,\n debugObjectName: this.atom_.name_,\n index: index,\n newValue: newValue,\n oldValue: oldValue\n } : null;\n // The reason why this is on right hand side here (and not above), is this way the uglifier will drop it, but it won't\n // cause any runtime overhead in development mode without NODE_ENV set, unless spying is enabled\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(change);\n }\n this.atom_.reportChanged();\n if (notify) {\n notifyListeners(this, change);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n };\n _proto.notifyArraySplice_ = function notifyArraySplice_(index, added, removed) {\n var notifySpy = !this.owned_ && isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"array\",\n object: this.proxy_,\n debugObjectName: this.atom_.name_,\n type: SPLICE,\n index: index,\n removed: removed,\n added: added,\n removedCount: removed.length,\n addedCount: added.length\n } : null;\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(change);\n }\n this.atom_.reportChanged();\n // conform: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe\n if (notify) {\n notifyListeners(this, change);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n };\n _proto.get_ = function get_(index) {\n if (this.legacyMode_ && index >= this.values_.length) {\n console.warn(process.env.NODE_ENV !== \"production\" ? \"[mobx.array] Attempt to read an array index (\" + index + \") that is out of bounds (\" + this.values_.length + \"). Please check length first. Out of bound indices will not be tracked by MobX\" : \"[mobx] Out of bounds read: \" + index);\n return undefined;\n }\n this.atom_.reportObserved();\n return this.dehanceValue_(this.values_[index]);\n };\n _proto.set_ = function set_(index, newValue) {\n var values = this.values_;\n if (this.legacyMode_ && index > values.length) {\n // out of bounds\n die(17, index, values.length);\n }\n if (index < values.length) {\n // update at index in range\n checkIfStateModificationsAreAllowed(this.atom_);\n var oldValue = values[index];\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: UPDATE,\n object: this.proxy_,\n index: index,\n newValue: newValue\n });\n if (!change) {\n return;\n }\n newValue = change.newValue;\n }\n newValue = this.enhancer_(newValue, oldValue);\n var changed = newValue !== oldValue;\n if (changed) {\n values[index] = newValue;\n this.notifyArrayChildUpdate_(index, newValue, oldValue);\n }\n } else {\n // For out of bound index, we don't create an actual sparse array,\n // but rather fill the holes with undefined (same as setArrayLength_).\n // This could be considered a bug.\n var newItems = new Array(index + 1 - values.length);\n for (var i = 0; i < newItems.length - 1; i++) {\n newItems[i] = undefined;\n } // No Array.fill everywhere...\n newItems[newItems.length - 1] = newValue;\n this.spliceWithArray_(values.length, 0, newItems);\n }\n };\n return ObservableArrayAdministration;\n}();\nfunction createObservableArray(initialValues, enhancer, name, owned) {\n if (name === void 0) {\n name = process.env.NODE_ENV !== \"production\" ? \"ObservableArray@\" + getNextId() : \"ObservableArray\";\n }\n if (owned === void 0) {\n owned = false;\n }\n assertProxies();\n return initObservable(function () {\n var adm = new ObservableArrayAdministration(name, enhancer, owned, false);\n addHiddenFinalProp(adm.values_, $mobx, adm);\n var proxy = new Proxy(adm.values_, arrayTraps);\n adm.proxy_ = proxy;\n if (initialValues && initialValues.length) {\n adm.spliceWithArray_(0, 0, initialValues);\n }\n return proxy;\n });\n}\n// eslint-disable-next-line\nvar arrayExtensions = {\n clear: function clear() {\n return this.splice(0);\n },\n replace: function replace(newItems) {\n var adm = this[$mobx];\n return adm.spliceWithArray_(0, adm.values_.length, newItems);\n },\n // Used by JSON.stringify\n toJSON: function toJSON() {\n return this.slice();\n },\n /*\n * functions that do alter the internal structure of the array, (based on lib.es6.d.ts)\n * since these functions alter the inner structure of the array, the have side effects.\n * Because the have side effects, they should not be used in computed function,\n * and for that reason the do not call dependencyState.notifyObserved\n */\n splice: function splice(index, deleteCount) {\n for (var _len = arguments.length, newItems = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n newItems[_key - 2] = arguments[_key];\n }\n var adm = this[$mobx];\n switch (arguments.length) {\n case 0:\n return [];\n case 1:\n return adm.spliceWithArray_(index);\n case 2:\n return adm.spliceWithArray_(index, deleteCount);\n }\n return adm.spliceWithArray_(index, deleteCount, newItems);\n },\n spliceWithArray: function spliceWithArray(index, deleteCount, newItems) {\n return this[$mobx].spliceWithArray_(index, deleteCount, newItems);\n },\n push: function push() {\n var adm = this[$mobx];\n for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n items[_key2] = arguments[_key2];\n }\n adm.spliceWithArray_(adm.values_.length, 0, items);\n return adm.values_.length;\n },\n pop: function pop() {\n return this.splice(Math.max(this[$mobx].values_.length - 1, 0), 1)[0];\n },\n shift: function shift() {\n return this.splice(0, 1)[0];\n },\n unshift: function unshift() {\n var adm = this[$mobx];\n for (var _len3 = arguments.length, items = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n items[_key3] = arguments[_key3];\n }\n adm.spliceWithArray_(0, 0, items);\n return adm.values_.length;\n },\n reverse: function reverse() {\n // reverse by default mutates in place before returning the result\n // which makes it both a 'derivation' and a 'mutation'.\n if (globalState.trackingDerivation) {\n die(37, \"reverse\");\n }\n this.replace(this.slice().reverse());\n return this;\n },\n sort: function sort() {\n // sort by default mutates in place before returning the result\n // which goes against all good practices. Let's not change the array in place!\n if (globalState.trackingDerivation) {\n die(37, \"sort\");\n }\n var copy = this.slice();\n copy.sort.apply(copy, arguments);\n this.replace(copy);\n return this;\n },\n remove: function remove(value) {\n var adm = this[$mobx];\n var idx = adm.dehanceValues_(adm.values_).indexOf(value);\n if (idx > -1) {\n this.splice(idx, 1);\n return true;\n }\n return false;\n }\n};\n/**\n * Wrap function from prototype\n * Without this, everything works as well, but this works\n * faster as everything works on unproxied values\n */\naddArrayExtension(\"at\", simpleFunc);\naddArrayExtension(\"concat\", simpleFunc);\naddArrayExtension(\"flat\", simpleFunc);\naddArrayExtension(\"includes\", simpleFunc);\naddArrayExtension(\"indexOf\", simpleFunc);\naddArrayExtension(\"join\", simpleFunc);\naddArrayExtension(\"lastIndexOf\", simpleFunc);\naddArrayExtension(\"slice\", simpleFunc);\naddArrayExtension(\"toString\", simpleFunc);\naddArrayExtension(\"toLocaleString\", simpleFunc);\naddArrayExtension(\"toSorted\", simpleFunc);\naddArrayExtension(\"toSpliced\", simpleFunc);\naddArrayExtension(\"with\", simpleFunc);\n// map\naddArrayExtension(\"every\", mapLikeFunc);\naddArrayExtension(\"filter\", mapLikeFunc);\naddArrayExtension(\"find\", mapLikeFunc);\naddArrayExtension(\"findIndex\", mapLikeFunc);\naddArrayExtension(\"findLast\", mapLikeFunc);\naddArrayExtension(\"findLastIndex\", mapLikeFunc);\naddArrayExtension(\"flatMap\", mapLikeFunc);\naddArrayExtension(\"forEach\", mapLikeFunc);\naddArrayExtension(\"map\", mapLikeFunc);\naddArrayExtension(\"some\", mapLikeFunc);\naddArrayExtension(\"toReversed\", mapLikeFunc);\n// reduce\naddArrayExtension(\"reduce\", reduceLikeFunc);\naddArrayExtension(\"reduceRight\", reduceLikeFunc);\nfunction addArrayExtension(funcName, funcFactory) {\n if (typeof Array.prototype[funcName] === \"function\") {\n arrayExtensions[funcName] = funcFactory(funcName);\n }\n}\n// Report and delegate to dehanced array\nfunction simpleFunc(funcName) {\n return function () {\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n return dehancedValues[funcName].apply(dehancedValues, arguments);\n };\n}\n// Make sure callbacks recieve correct array arg #2326\nfunction mapLikeFunc(funcName) {\n return function (callback, thisArg) {\n var _this2 = this;\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n return dehancedValues[funcName](function (element, index) {\n return callback.call(thisArg, element, index, _this2);\n });\n };\n}\n// Make sure callbacks recieve correct array arg #2326\nfunction reduceLikeFunc(funcName) {\n return function () {\n var _this3 = this;\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n // #2432 - reduce behavior depends on arguments.length\n var callback = arguments[0];\n arguments[0] = function (accumulator, currentValue, index) {\n return callback(accumulator, currentValue, index, _this3);\n };\n return dehancedValues[funcName].apply(dehancedValues, arguments);\n };\n}\nvar isObservableArrayAdministration = /*#__PURE__*/createInstanceofPredicate(\"ObservableArrayAdministration\", ObservableArrayAdministration);\nfunction isObservableArray(thing) {\n return isObject(thing) && isObservableArrayAdministration(thing[$mobx]);\n}\n\nvar _Symbol$iterator, _Symbol$toStringTag;\nvar ObservableMapMarker = {};\nvar ADD = \"add\";\nvar DELETE = \"delete\";\n// just extend Map? See also https://gist.github.com/nestharus/13b4d74f2ef4a2f4357dbd3fc23c1e54\n// But: https://github.com/mobxjs/mobx/issues/1556\n_Symbol$iterator = Symbol.iterator;\n_Symbol$toStringTag = Symbol.toStringTag;\nvar ObservableMap = /*#__PURE__*/function () {\n // hasMap, not hashMap >-).\n\n function ObservableMap(initialData, enhancer_, name_) {\n var _this = this;\n if (enhancer_ === void 0) {\n enhancer_ = deepEnhancer;\n }\n if (name_ === void 0) {\n name_ = process.env.NODE_ENV !== \"production\" ? \"ObservableMap@\" + getNextId() : \"ObservableMap\";\n }\n this.enhancer_ = void 0;\n this.name_ = void 0;\n this[$mobx] = ObservableMapMarker;\n this.data_ = void 0;\n this.hasMap_ = void 0;\n this.keysAtom_ = void 0;\n this.interceptors_ = void 0;\n this.changeListeners_ = void 0;\n this.dehancer = void 0;\n this.enhancer_ = enhancer_;\n this.name_ = name_;\n if (!isFunction(Map)) {\n die(18);\n }\n initObservable(function () {\n _this.keysAtom_ = createAtom(process.env.NODE_ENV !== \"production\" ? _this.name_ + \".keys()\" : \"ObservableMap.keys()\");\n _this.data_ = new Map();\n _this.hasMap_ = new Map();\n if (initialData) {\n _this.merge(initialData);\n }\n });\n }\n var _proto = ObservableMap.prototype;\n _proto.has_ = function has_(key) {\n return this.data_.has(key);\n };\n _proto.has = function has(key) {\n var _this2 = this;\n if (!globalState.trackingDerivation) {\n return this.has_(key);\n }\n var entry = this.hasMap_.get(key);\n if (!entry) {\n var newEntry = entry = new ObservableValue(this.has_(key), referenceEnhancer, process.env.NODE_ENV !== \"production\" ? this.name_ + \".\" + stringifyKey(key) + \"?\" : \"ObservableMap.key?\", false);\n this.hasMap_.set(key, newEntry);\n onBecomeUnobserved(newEntry, function () {\n return _this2.hasMap_[\"delete\"](key);\n });\n }\n return entry.get();\n };\n _proto.set = function set(key, value) {\n var hasKey = this.has_(key);\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: hasKey ? UPDATE : ADD,\n object: this,\n newValue: value,\n name: key\n });\n if (!change) {\n return this;\n }\n value = change.newValue;\n }\n if (hasKey) {\n this.updateValue_(key, value);\n } else {\n this.addValue_(key, value);\n }\n return this;\n };\n _proto[\"delete\"] = function _delete(key) {\n var _this3 = this;\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: DELETE,\n object: this,\n name: key\n });\n if (!change) {\n return false;\n }\n }\n if (this.has_(key)) {\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var _change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: DELETE,\n object: this,\n oldValue: this.data_.get(key).value_,\n name: key\n } : null;\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(_change);\n } // TODO fix type\n transaction(function () {\n var _this3$hasMap_$get;\n _this3.keysAtom_.reportChanged();\n (_this3$hasMap_$get = _this3.hasMap_.get(key)) == null ? void 0 : _this3$hasMap_$get.setNewValue_(false);\n var observable = _this3.data_.get(key);\n observable.setNewValue_(undefined);\n _this3.data_[\"delete\"](key);\n });\n if (notify) {\n notifyListeners(this, _change);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n return true;\n }\n return false;\n };\n _proto.updateValue_ = function updateValue_(key, newValue) {\n var observable = this.data_.get(key);\n newValue = observable.prepareNewValue_(newValue);\n if (newValue !== globalState.UNCHANGED) {\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: UPDATE,\n object: this,\n oldValue: observable.value_,\n name: key,\n newValue: newValue\n } : null;\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(change);\n } // TODO fix type\n observable.setNewValue_(newValue);\n if (notify) {\n notifyListeners(this, change);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n }\n };\n _proto.addValue_ = function addValue_(key, newValue) {\n var _this4 = this;\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n transaction(function () {\n var _this4$hasMap_$get;\n var observable = new ObservableValue(newValue, _this4.enhancer_, process.env.NODE_ENV !== \"production\" ? _this4.name_ + \".\" + stringifyKey(key) : \"ObservableMap.key\", false);\n _this4.data_.set(key, observable);\n newValue = observable.value_; // value might have been changed\n (_this4$hasMap_$get = _this4.hasMap_.get(key)) == null ? void 0 : _this4$hasMap_$get.setNewValue_(true);\n _this4.keysAtom_.reportChanged();\n });\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: ADD,\n object: this,\n name: key,\n newValue: newValue\n } : null;\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(change);\n } // TODO fix type\n if (notify) {\n notifyListeners(this, change);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n };\n _proto.get = function get(key) {\n if (this.has(key)) {\n return this.dehanceValue_(this.data_.get(key).get());\n }\n return this.dehanceValue_(undefined);\n };\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n return value;\n };\n _proto.keys = function keys() {\n this.keysAtom_.reportObserved();\n return this.data_.keys();\n };\n _proto.values = function values() {\n var self = this;\n var keys = this.keys();\n return makeIterable({\n next: function next() {\n var _keys$next = keys.next(),\n done = _keys$next.done,\n value = _keys$next.value;\n return {\n done: done,\n value: done ? undefined : self.get(value)\n };\n }\n });\n };\n _proto.entries = function entries() {\n var self = this;\n var keys = this.keys();\n return makeIterable({\n next: function next() {\n var _keys$next2 = keys.next(),\n done = _keys$next2.done,\n value = _keys$next2.value;\n return {\n done: done,\n value: done ? undefined : [value, self.get(value)]\n };\n }\n });\n };\n _proto[_Symbol$iterator] = function () {\n return this.entries();\n };\n _proto.forEach = function forEach(callback, thisArg) {\n for (var _iterator = _createForOfIteratorHelperLoose(this), _step; !(_step = _iterator()).done;) {\n var _step$value = _step.value,\n key = _step$value[0],\n value = _step$value[1];\n callback.call(thisArg, value, key, this);\n }\n }\n /** Merge another object into this object, returns this. */;\n _proto.merge = function merge(other) {\n var _this5 = this;\n if (isObservableMap(other)) {\n other = new Map(other);\n }\n transaction(function () {\n if (isPlainObject(other)) {\n getPlainObjectKeys(other).forEach(function (key) {\n return _this5.set(key, other[key]);\n });\n } else if (Array.isArray(other)) {\n other.forEach(function (_ref) {\n var key = _ref[0],\n value = _ref[1];\n return _this5.set(key, value);\n });\n } else if (isES6Map(other)) {\n if (other.constructor !== Map) {\n die(19, other);\n }\n other.forEach(function (value, key) {\n return _this5.set(key, value);\n });\n } else if (other !== null && other !== undefined) {\n die(20, other);\n }\n });\n return this;\n };\n _proto.clear = function clear() {\n var _this6 = this;\n transaction(function () {\n untracked(function () {\n for (var _iterator2 = _createForOfIteratorHelperLoose(_this6.keys()), _step2; !(_step2 = _iterator2()).done;) {\n var key = _step2.value;\n _this6[\"delete\"](key);\n }\n });\n });\n };\n _proto.replace = function replace(values) {\n var _this7 = this;\n // Implementation requirements:\n // - respect ordering of replacement map\n // - allow interceptors to run and potentially prevent individual operations\n // - don't recreate observables that already exist in original map (so we don't destroy existing subscriptions)\n // - don't _keysAtom.reportChanged if the keys of resulting map are indentical (order matters!)\n // - note that result map may differ from replacement map due to the interceptors\n transaction(function () {\n // Convert to map so we can do quick key lookups\n var replacementMap = convertToMap(values);\n var orderedData = new Map();\n // Used for optimization\n var keysReportChangedCalled = false;\n // Delete keys that don't exist in replacement map\n // if the key deletion is prevented by interceptor\n // add entry at the beginning of the result map\n for (var _iterator3 = _createForOfIteratorHelperLoose(_this7.data_.keys()), _step3; !(_step3 = _iterator3()).done;) {\n var key = _step3.value;\n // Concurrently iterating/deleting keys\n // iterator should handle this correctly\n if (!replacementMap.has(key)) {\n var deleted = _this7[\"delete\"](key);\n // Was the key removed?\n if (deleted) {\n // _keysAtom.reportChanged() was already called\n keysReportChangedCalled = true;\n } else {\n // Delete prevented by interceptor\n var value = _this7.data_.get(key);\n orderedData.set(key, value);\n }\n }\n }\n // Merge entries\n for (var _iterator4 = _createForOfIteratorHelperLoose(replacementMap.entries()), _step4; !(_step4 = _iterator4()).done;) {\n var _step4$value = _step4.value,\n _key = _step4$value[0],\n _value = _step4$value[1];\n // We will want to know whether a new key is added\n var keyExisted = _this7.data_.has(_key);\n // Add or update value\n _this7.set(_key, _value);\n // The addition could have been prevent by interceptor\n if (_this7.data_.has(_key)) {\n // The update could have been prevented by interceptor\n // and also we want to preserve existing values\n // so use value from _data map (instead of replacement map)\n var _value2 = _this7.data_.get(_key);\n orderedData.set(_key, _value2);\n // Was a new key added?\n if (!keyExisted) {\n // _keysAtom.reportChanged() was already called\n keysReportChangedCalled = true;\n }\n }\n }\n // Check for possible key order change\n if (!keysReportChangedCalled) {\n if (_this7.data_.size !== orderedData.size) {\n // If size differs, keys are definitely modified\n _this7.keysAtom_.reportChanged();\n } else {\n var iter1 = _this7.data_.keys();\n var iter2 = orderedData.keys();\n var next1 = iter1.next();\n var next2 = iter2.next();\n while (!next1.done) {\n if (next1.value !== next2.value) {\n _this7.keysAtom_.reportChanged();\n break;\n }\n next1 = iter1.next();\n next2 = iter2.next();\n }\n }\n }\n // Use correctly ordered map\n _this7.data_ = orderedData;\n });\n return this;\n };\n _proto.toString = function toString() {\n return \"[object ObservableMap]\";\n };\n _proto.toJSON = function toJSON() {\n return Array.from(this);\n };\n /**\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\n * for callback details\n */\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (process.env.NODE_ENV !== \"production\" && fireImmediately === true) {\n die(\"`observe` doesn't support fireImmediately=true in combination with maps.\");\n }\n return registerListener(this, listener);\n };\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n _createClass(ObservableMap, [{\n key: \"size\",\n get: function get() {\n this.keysAtom_.reportObserved();\n return this.data_.size;\n }\n }, {\n key: _Symbol$toStringTag,\n get: function get() {\n return \"Map\";\n }\n }]);\n return ObservableMap;\n}();\n// eslint-disable-next-line\nvar isObservableMap = /*#__PURE__*/createInstanceofPredicate(\"ObservableMap\", ObservableMap);\nfunction convertToMap(dataStructure) {\n if (isES6Map(dataStructure) || isObservableMap(dataStructure)) {\n return dataStructure;\n } else if (Array.isArray(dataStructure)) {\n return new Map(dataStructure);\n } else if (isPlainObject(dataStructure)) {\n var map = new Map();\n for (var key in dataStructure) {\n map.set(key, dataStructure[key]);\n }\n return map;\n } else {\n return die(21, dataStructure);\n }\n}\n\nvar _Symbol$iterator$1, _Symbol$toStringTag$1;\nvar ObservableSetMarker = {};\n_Symbol$iterator$1 = Symbol.iterator;\n_Symbol$toStringTag$1 = Symbol.toStringTag;\nvar ObservableSet = /*#__PURE__*/function () {\n function ObservableSet(initialData, enhancer, name_) {\n var _this = this;\n if (enhancer === void 0) {\n enhancer = deepEnhancer;\n }\n if (name_ === void 0) {\n name_ = process.env.NODE_ENV !== \"production\" ? \"ObservableSet@\" + getNextId() : \"ObservableSet\";\n }\n this.name_ = void 0;\n this[$mobx] = ObservableSetMarker;\n this.data_ = new Set();\n this.atom_ = void 0;\n this.changeListeners_ = void 0;\n this.interceptors_ = void 0;\n this.dehancer = void 0;\n this.enhancer_ = void 0;\n this.name_ = name_;\n if (!isFunction(Set)) {\n die(22);\n }\n this.enhancer_ = function (newV, oldV) {\n return enhancer(newV, oldV, name_);\n };\n initObservable(function () {\n _this.atom_ = createAtom(_this.name_);\n if (initialData) {\n _this.replace(initialData);\n }\n });\n }\n var _proto = ObservableSet.prototype;\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n return value;\n };\n _proto.clear = function clear() {\n var _this2 = this;\n transaction(function () {\n untracked(function () {\n for (var _iterator = _createForOfIteratorHelperLoose(_this2.data_.values()), _step; !(_step = _iterator()).done;) {\n var value = _step.value;\n _this2[\"delete\"](value);\n }\n });\n });\n };\n _proto.forEach = function forEach(callbackFn, thisArg) {\n for (var _iterator2 = _createForOfIteratorHelperLoose(this), _step2; !(_step2 = _iterator2()).done;) {\n var value = _step2.value;\n callbackFn.call(thisArg, value, value, this);\n }\n };\n _proto.add = function add(value) {\n var _this3 = this;\n checkIfStateModificationsAreAllowed(this.atom_);\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: ADD,\n object: this,\n newValue: value\n });\n if (!change) {\n return this;\n }\n // ideally, value = change.value would be done here, so that values can be\n // changed by interceptor. Same applies for other Set and Map api's.\n }\n\n if (!this.has(value)) {\n transaction(function () {\n _this3.data_.add(_this3.enhancer_(value, undefined));\n _this3.atom_.reportChanged();\n });\n var notifySpy = process.env.NODE_ENV !== \"production\" && isSpyEnabled();\n var notify = hasListeners(this);\n var _change = notify || notifySpy ? {\n observableKind: \"set\",\n debugObjectName: this.name_,\n type: ADD,\n object: this,\n newValue: value\n } : null;\n if (notifySpy && process.env.NODE_ENV !== \"production\") {\n spyReportStart(_change);\n }\n if (notify) {\n notifyListeners(this, _change);\n }\n if (notifySpy && process.env.NODE_ENV !== \"production\") {\n spyReportEnd();\n }\n }\n return this;\n };\n _proto[\"delete\"] = function _delete(value) {\n var _this4 = this;\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: DELETE,\n object: this,\n oldValue: value\n });\n if (!change) {\n return false;\n }\n }\n if (this.has(value)) {\n var notifySpy = process.env.NODE_ENV !== \"production\" && isSpyEnabled();\n var notify = hasListeners(this);\n var _change2 = notify || notifySpy ? {\n observableKind: \"set\",\n debugObjectName: this.name_,\n type: DELETE,\n object: this,\n oldValue: value\n } : null;\n if (notifySpy && process.env.NODE_ENV !== \"production\") {\n spyReportStart(_change2);\n }\n transaction(function () {\n _this4.atom_.reportChanged();\n _this4.data_[\"delete\"](value);\n });\n if (notify) {\n notifyListeners(this, _change2);\n }\n if (notifySpy && process.env.NODE_ENV !== \"production\") {\n spyReportEnd();\n }\n return true;\n }\n return false;\n };\n _proto.has = function has(value) {\n this.atom_.reportObserved();\n return this.data_.has(this.dehanceValue_(value));\n };\n _proto.entries = function entries() {\n var nextIndex = 0;\n var keys = Array.from(this.keys());\n var values = Array.from(this.values());\n return makeIterable({\n next: function next() {\n var index = nextIndex;\n nextIndex += 1;\n return index < values.length ? {\n value: [keys[index], values[index]],\n done: false\n } : {\n done: true\n };\n }\n });\n };\n _proto.keys = function keys() {\n return this.values();\n };\n _proto.values = function values() {\n this.atom_.reportObserved();\n var self = this;\n var nextIndex = 0;\n var observableValues = Array.from(this.data_.values());\n return makeIterable({\n next: function next() {\n return nextIndex < observableValues.length ? {\n value: self.dehanceValue_(observableValues[nextIndex++]),\n done: false\n } : {\n done: true\n };\n }\n });\n };\n _proto.replace = function replace(other) {\n var _this5 = this;\n if (isObservableSet(other)) {\n other = new Set(other);\n }\n transaction(function () {\n if (Array.isArray(other)) {\n _this5.clear();\n other.forEach(function (value) {\n return _this5.add(value);\n });\n } else if (isES6Set(other)) {\n _this5.clear();\n other.forEach(function (value) {\n return _this5.add(value);\n });\n } else if (other !== null && other !== undefined) {\n die(\"Cannot initialize set from \" + other);\n }\n });\n return this;\n };\n _proto.observe_ = function observe_(listener, fireImmediately) {\n // ... 'fireImmediately' could also be true?\n if (process.env.NODE_ENV !== \"production\" && fireImmediately === true) {\n die(\"`observe` doesn't support fireImmediately=true in combination with sets.\");\n }\n return registerListener(this, listener);\n };\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n _proto.toJSON = function toJSON() {\n return Array.from(this);\n };\n _proto.toString = function toString() {\n return \"[object ObservableSet]\";\n };\n _proto[_Symbol$iterator$1] = function () {\n return this.values();\n };\n _createClass(ObservableSet, [{\n key: \"size\",\n get: function get() {\n this.atom_.reportObserved();\n return this.data_.size;\n }\n }, {\n key: _Symbol$toStringTag$1,\n get: function get() {\n return \"Set\";\n }\n }]);\n return ObservableSet;\n}();\n// eslint-disable-next-line\nvar isObservableSet = /*#__PURE__*/createInstanceofPredicate(\"ObservableSet\", ObservableSet);\n\nvar descriptorCache = /*#__PURE__*/Object.create(null);\nvar REMOVE = \"remove\";\nvar ObservableObjectAdministration = /*#__PURE__*/function () {\n function ObservableObjectAdministration(target_, values_, name_,\n // Used anytime annotation is not explicitely provided\n defaultAnnotation_) {\n if (values_ === void 0) {\n values_ = new Map();\n }\n if (defaultAnnotation_ === void 0) {\n defaultAnnotation_ = autoAnnotation;\n }\n this.target_ = void 0;\n this.values_ = void 0;\n this.name_ = void 0;\n this.defaultAnnotation_ = void 0;\n this.keysAtom_ = void 0;\n this.changeListeners_ = void 0;\n this.interceptors_ = void 0;\n this.proxy_ = void 0;\n this.isPlainObject_ = void 0;\n this.appliedAnnotations_ = void 0;\n this.pendingKeys_ = void 0;\n this.target_ = target_;\n this.values_ = values_;\n this.name_ = name_;\n this.defaultAnnotation_ = defaultAnnotation_;\n this.keysAtom_ = new Atom(process.env.NODE_ENV !== \"production\" ? this.name_ + \".keys\" : \"ObservableObject.keys\");\n // Optimization: we use this frequently\n this.isPlainObject_ = isPlainObject(this.target_);\n if (process.env.NODE_ENV !== \"production\" && !isAnnotation(this.defaultAnnotation_)) {\n die(\"defaultAnnotation must be valid annotation\");\n }\n if (process.env.NODE_ENV !== \"production\") {\n // Prepare structure for tracking which fields were already annotated\n this.appliedAnnotations_ = {};\n }\n }\n var _proto = ObservableObjectAdministration.prototype;\n _proto.getObservablePropValue_ = function getObservablePropValue_(key) {\n return this.values_.get(key).get();\n };\n _proto.setObservablePropValue_ = function setObservablePropValue_(key, newValue) {\n var observable = this.values_.get(key);\n if (observable instanceof ComputedValue) {\n observable.set(newValue);\n return true;\n }\n // intercept\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: UPDATE,\n object: this.proxy_ || this.target_,\n name: key,\n newValue: newValue\n });\n if (!change) {\n return null;\n }\n newValue = change.newValue;\n }\n newValue = observable.prepareNewValue_(newValue);\n // notify spy & observers\n if (newValue !== globalState.UNCHANGED) {\n var notify = hasListeners(this);\n var notifySpy = process.env.NODE_ENV !== \"production\" && isSpyEnabled();\n var _change = notify || notifySpy ? {\n type: UPDATE,\n observableKind: \"object\",\n debugObjectName: this.name_,\n object: this.proxy_ || this.target_,\n oldValue: observable.value_,\n name: key,\n newValue: newValue\n } : null;\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(_change);\n }\n observable.setNewValue_(newValue);\n if (notify) {\n notifyListeners(this, _change);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n }\n return true;\n };\n _proto.get_ = function get_(key) {\n if (globalState.trackingDerivation && !hasProp(this.target_, key)) {\n // Key doesn't exist yet, subscribe for it in case it's added later\n this.has_(key);\n }\n return this.target_[key];\n }\n /**\n * @param {PropertyKey} key\n * @param {any} value\n * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is\n * @param {boolean} proxyTrap whether it's called from proxy trap\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\n */;\n _proto.set_ = function set_(key, value, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n // Don't use .has(key) - we care about own\n if (hasProp(this.target_, key)) {\n // Existing prop\n if (this.values_.has(key)) {\n // Observable (can be intercepted)\n return this.setObservablePropValue_(key, value);\n } else if (proxyTrap) {\n // Non-observable - proxy\n return Reflect.set(this.target_, key, value);\n } else {\n // Non-observable\n this.target_[key] = value;\n return true;\n }\n } else {\n // New prop\n return this.extend_(key, {\n value: value,\n enumerable: true,\n writable: true,\n configurable: true\n }, this.defaultAnnotation_, proxyTrap);\n }\n }\n // Trap for \"in\"\n ;\n _proto.has_ = function has_(key) {\n if (!globalState.trackingDerivation) {\n // Skip key subscription outside derivation\n return key in this.target_;\n }\n this.pendingKeys_ || (this.pendingKeys_ = new Map());\n var entry = this.pendingKeys_.get(key);\n if (!entry) {\n entry = new ObservableValue(key in this.target_, referenceEnhancer, process.env.NODE_ENV !== \"production\" ? this.name_ + \".\" + stringifyKey(key) + \"?\" : \"ObservableObject.key?\", false);\n this.pendingKeys_.set(key, entry);\n }\n return entry.get();\n }\n /**\n * @param {PropertyKey} key\n * @param {Annotation|boolean} annotation true - use default annotation, false - ignore prop\n */;\n _proto.make_ = function make_(key, annotation) {\n if (annotation === true) {\n annotation = this.defaultAnnotation_;\n }\n if (annotation === false) {\n return;\n }\n assertAnnotable(this, annotation, key);\n if (!(key in this.target_)) {\n var _this$target_$storedA;\n // Throw on missing key, except for decorators:\n // Decorator annotations are collected from whole prototype chain.\n // When called from super() some props may not exist yet.\n // However we don't have to worry about missing prop,\n // because the decorator must have been applied to something.\n if ((_this$target_$storedA = this.target_[storedAnnotationsSymbol]) != null && _this$target_$storedA[key]) {\n return; // will be annotated by subclass constructor\n } else {\n die(1, annotation.annotationType_, this.name_ + \".\" + key.toString());\n }\n }\n var source = this.target_;\n while (source && source !== objectPrototype) {\n var descriptor = getDescriptor(source, key);\n if (descriptor) {\n var outcome = annotation.make_(this, key, descriptor, source);\n if (outcome === 0 /* MakeResult.Cancel */) {\n return;\n }\n if (outcome === 1 /* MakeResult.Break */) {\n break;\n }\n }\n source = Object.getPrototypeOf(source);\n }\n recordAnnotationApplied(this, annotation, key);\n }\n /**\n * @param {PropertyKey} key\n * @param {PropertyDescriptor} descriptor\n * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is\n * @param {boolean} proxyTrap whether it's called from proxy trap\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\n */;\n _proto.extend_ = function extend_(key, descriptor, annotation, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n if (annotation === true) {\n annotation = this.defaultAnnotation_;\n }\n if (annotation === false) {\n return this.defineProperty_(key, descriptor, proxyTrap);\n }\n assertAnnotable(this, annotation, key);\n var outcome = annotation.extend_(this, key, descriptor, proxyTrap);\n if (outcome) {\n recordAnnotationApplied(this, annotation, key);\n }\n return outcome;\n }\n /**\n * @param {PropertyKey} key\n * @param {PropertyDescriptor} descriptor\n * @param {boolean} proxyTrap whether it's called from proxy trap\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\n */;\n _proto.defineProperty_ = function defineProperty_(key, descriptor, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n try {\n startBatch();\n // Delete\n var deleteOutcome = this.delete_(key);\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n }\n // ADD interceptor\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: descriptor.value\n });\n if (!change) {\n return null;\n }\n var newValue = change.newValue;\n if (descriptor.value !== newValue) {\n descriptor = _extends({}, descriptor, {\n value: newValue\n });\n }\n }\n // Define\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n // Notify\n this.notifyPropertyAddition_(key, descriptor.value);\n } finally {\n endBatch();\n }\n return true;\n }\n // If original descriptor becomes relevant, move this to annotation directly\n ;\n _proto.defineObservableProperty_ = function defineObservableProperty_(key, value, enhancer, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n try {\n startBatch();\n // Delete\n var deleteOutcome = this.delete_(key);\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n }\n // ADD interceptor\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: value\n });\n if (!change) {\n return null;\n }\n value = change.newValue;\n }\n var cachedDescriptor = getCachedObservablePropDescriptor(key);\n var descriptor = {\n configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,\n enumerable: true,\n get: cachedDescriptor.get,\n set: cachedDescriptor.set\n };\n // Define\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n var observable = new ObservableValue(value, enhancer, process.env.NODE_ENV !== \"production\" ? this.name_ + \".\" + key.toString() : \"ObservableObject.key\", false);\n this.values_.set(key, observable);\n // Notify (value possibly changed by ObservableValue)\n this.notifyPropertyAddition_(key, observable.value_);\n } finally {\n endBatch();\n }\n return true;\n }\n // If original descriptor becomes relevant, move this to annotation directly\n ;\n _proto.defineComputedProperty_ = function defineComputedProperty_(key, options, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n try {\n startBatch();\n // Delete\n var deleteOutcome = this.delete_(key);\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n }\n // ADD interceptor\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: undefined\n });\n if (!change) {\n return null;\n }\n }\n options.name || (options.name = process.env.NODE_ENV !== \"production\" ? this.name_ + \".\" + key.toString() : \"ObservableObject.key\");\n options.context = this.proxy_ || this.target_;\n var cachedDescriptor = getCachedObservablePropDescriptor(key);\n var descriptor = {\n configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,\n enumerable: false,\n get: cachedDescriptor.get,\n set: cachedDescriptor.set\n };\n // Define\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n this.values_.set(key, new ComputedValue(options));\n // Notify\n this.notifyPropertyAddition_(key, undefined);\n } finally {\n endBatch();\n }\n return true;\n }\n /**\n * @param {PropertyKey} key\n * @param {PropertyDescriptor} descriptor\n * @param {boolean} proxyTrap whether it's called from proxy trap\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\n */;\n _proto.delete_ = function delete_(key, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n // No such prop\n if (!hasProp(this.target_, key)) {\n return true;\n }\n // Intercept\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: REMOVE\n });\n // Cancelled\n if (!change) {\n return null;\n }\n }\n // Delete\n try {\n var _this$pendingKeys_, _this$pendingKeys_$ge;\n startBatch();\n var notify = hasListeners(this);\n var notifySpy = process.env.NODE_ENV !== \"production\" && isSpyEnabled();\n var observable = this.values_.get(key);\n // Value needed for spies/listeners\n var value = undefined;\n // Optimization: don't pull the value unless we will need it\n if (!observable && (notify || notifySpy)) {\n var _getDescriptor;\n value = (_getDescriptor = getDescriptor(this.target_, key)) == null ? void 0 : _getDescriptor.value;\n }\n // delete prop (do first, may fail)\n if (proxyTrap) {\n if (!Reflect.deleteProperty(this.target_, key)) {\n return false;\n }\n } else {\n delete this.target_[key];\n }\n // Allow re-annotating this field\n if (process.env.NODE_ENV !== \"production\") {\n delete this.appliedAnnotations_[key];\n }\n // Clear observable\n if (observable) {\n this.values_[\"delete\"](key);\n // for computed, value is undefined\n if (observable instanceof ObservableValue) {\n value = observable.value_;\n }\n // Notify: autorun(() => obj[key]), see #1796\n propagateChanged(observable);\n }\n // Notify \"keys/entries/values\" observers\n this.keysAtom_.reportChanged();\n // Notify \"has\" observers\n // \"in\" as it may still exist in proto\n (_this$pendingKeys_ = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_$ge = _this$pendingKeys_.get(key)) == null ? void 0 : _this$pendingKeys_$ge.set(key in this.target_);\n // Notify spies/listeners\n if (notify || notifySpy) {\n var _change2 = {\n type: REMOVE,\n observableKind: \"object\",\n object: this.proxy_ || this.target_,\n debugObjectName: this.name_,\n oldValue: value,\n name: key\n };\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(_change2);\n }\n if (notify) {\n notifyListeners(this, _change2);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n }\n } finally {\n endBatch();\n }\n return true;\n }\n /**\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\n * for callback details\n */;\n _proto.observe_ = function observe_(callback, fireImmediately) {\n if (process.env.NODE_ENV !== \"production\" && fireImmediately === true) {\n die(\"`observe` doesn't support the fire immediately property for observable objects.\");\n }\n return registerListener(this, callback);\n };\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n _proto.notifyPropertyAddition_ = function notifyPropertyAddition_(key, value) {\n var _this$pendingKeys_2, _this$pendingKeys_2$g;\n var notify = hasListeners(this);\n var notifySpy = process.env.NODE_ENV !== \"production\" && isSpyEnabled();\n if (notify || notifySpy) {\n var change = notify || notifySpy ? {\n type: ADD,\n observableKind: \"object\",\n debugObjectName: this.name_,\n object: this.proxy_ || this.target_,\n name: key,\n newValue: value\n } : null;\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportStart(change);\n }\n if (notify) {\n notifyListeners(this, change);\n }\n if (process.env.NODE_ENV !== \"production\" && notifySpy) {\n spyReportEnd();\n }\n }\n (_this$pendingKeys_2 = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_2$g = _this$pendingKeys_2.get(key)) == null ? void 0 : _this$pendingKeys_2$g.set(true);\n // Notify \"keys/entries/values\" observers\n this.keysAtom_.reportChanged();\n };\n _proto.ownKeys_ = function ownKeys_() {\n this.keysAtom_.reportObserved();\n return ownKeys(this.target_);\n };\n _proto.keys_ = function keys_() {\n // Returns enumerable && own, but unfortunately keysAtom will report on ANY key change.\n // There is no way to distinguish between Object.keys(object) and Reflect.ownKeys(object) - both are handled by ownKeys trap.\n // We can either over-report in Object.keys(object) or under-report in Reflect.ownKeys(object)\n // We choose to over-report in Object.keys(object), because:\n // - typically it's used with simple data objects\n // - when symbolic/non-enumerable keys are relevant Reflect.ownKeys works as expected\n this.keysAtom_.reportObserved();\n return Object.keys(this.target_);\n };\n return ObservableObjectAdministration;\n}();\nfunction asObservableObject(target, options) {\n var _options$name;\n if (process.env.NODE_ENV !== \"production\" && options && isObservableObject(target)) {\n die(\"Options can't be provided for already observable objects.\");\n }\n if (hasProp(target, $mobx)) {\n if (process.env.NODE_ENV !== \"production\" && !(getAdministration(target) instanceof ObservableObjectAdministration)) {\n die(\"Cannot convert '\" + getDebugName(target) + \"' into observable object:\" + \"\\nThe target is already observable of different type.\" + \"\\nExtending builtins is not supported.\");\n }\n return target;\n }\n if (process.env.NODE_ENV !== \"production\" && !Object.isExtensible(target)) {\n die(\"Cannot make the designated object observable; it is not extensible\");\n }\n var name = (_options$name = options == null ? void 0 : options.name) != null ? _options$name : process.env.NODE_ENV !== \"production\" ? (isPlainObject(target) ? \"ObservableObject\" : target.constructor.name) + \"@\" + getNextId() : \"ObservableObject\";\n var adm = new ObservableObjectAdministration(target, new Map(), String(name), getAnnotationFromOptions(options));\n addHiddenProp(target, $mobx, adm);\n return target;\n}\nvar isObservableObjectAdministration = /*#__PURE__*/createInstanceofPredicate(\"ObservableObjectAdministration\", ObservableObjectAdministration);\nfunction getCachedObservablePropDescriptor(key) {\n return descriptorCache[key] || (descriptorCache[key] = {\n get: function get() {\n return this[$mobx].getObservablePropValue_(key);\n },\n set: function set(value) {\n return this[$mobx].setObservablePropValue_(key, value);\n }\n });\n}\nfunction isObservableObject(thing) {\n if (isObject(thing)) {\n return isObservableObjectAdministration(thing[$mobx]);\n }\n return false;\n}\nfunction recordAnnotationApplied(adm, annotation, key) {\n var _adm$target_$storedAn;\n if (process.env.NODE_ENV !== \"production\") {\n adm.appliedAnnotations_[key] = annotation;\n }\n // Remove applied decorator annotation so we don't try to apply it again in subclass constructor\n (_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null ? true : delete _adm$target_$storedAn[key];\n}\nfunction assertAnnotable(adm, annotation, key) {\n // Valid annotation\n if (process.env.NODE_ENV !== \"production\" && !isAnnotation(annotation)) {\n die(\"Cannot annotate '\" + adm.name_ + \".\" + key.toString() + \"': Invalid annotation.\");\n }\n /*\n // Configurable, not sealed, not frozen\n // Possibly not needed, just a little better error then the one thrown by engine.\n // Cases where this would be useful the most (subclass field initializer) are not interceptable by this.\n if (__DEV__) {\n const configurable = getDescriptor(adm.target_, key)?.configurable\n const frozen = Object.isFrozen(adm.target_)\n const sealed = Object.isSealed(adm.target_)\n if (!configurable || frozen || sealed) {\n const fieldName = `${adm.name_}.${key.toString()}`\n const requestedAnnotationType = annotation.annotationType_\n let error = `Cannot apply '${requestedAnnotationType}' to '${fieldName}':`\n if (frozen) {\n error += `\\nObject is frozen.`\n }\n if (sealed) {\n error += `\\nObject is sealed.`\n }\n if (!configurable) {\n error += `\\nproperty is not configurable.`\n // Mention only if caused by us to avoid confusion\n if (hasProp(adm.appliedAnnotations!, key)) {\n error += `\\nTo prevent accidental re-definition of a field by a subclass, `\n error += `all annotated fields of non-plain objects (classes) are not configurable.`\n }\n }\n die(error)\n }\n }\n */\n // Not annotated\n if (process.env.NODE_ENV !== \"production\" && !isOverride(annotation) && hasProp(adm.appliedAnnotations_, key)) {\n var fieldName = adm.name_ + \".\" + key.toString();\n var currentAnnotationType = adm.appliedAnnotations_[key].annotationType_;\n var requestedAnnotationType = annotation.annotationType_;\n die(\"Cannot apply '\" + requestedAnnotationType + \"' to '\" + fieldName + \"':\" + (\"\\nThe field is already annotated with '\" + currentAnnotationType + \"'.\") + \"\\nRe-annotating fields is not allowed.\" + \"\\nUse 'override' annotation for methods overridden by subclass.\");\n }\n}\n\n// Bug in safari 9.* (or iOS 9 safari mobile). See #364\nvar ENTRY_0 = /*#__PURE__*/createArrayEntryDescriptor(0);\nvar safariPrototypeSetterInheritanceBug = /*#__PURE__*/function () {\n var v = false;\n var p = {};\n Object.defineProperty(p, \"0\", {\n set: function set() {\n v = true;\n }\n });\n /*#__PURE__*/Object.create(p)[\"0\"] = 1;\n return v === false;\n}();\n/**\n * This array buffer contains two lists of properties, so that all arrays\n * can recycle their property definitions, which significantly improves performance of creating\n * properties on the fly.\n */\nvar OBSERVABLE_ARRAY_BUFFER_SIZE = 0;\n// Typescript workaround to make sure ObservableArray extends Array\nvar StubArray = function StubArray() {};\nfunction inherit(ctor, proto) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(ctor.prototype, proto);\n } else if (ctor.prototype.__proto__ !== undefined) {\n ctor.prototype.__proto__ = proto;\n } else {\n ctor.prototype = proto;\n }\n}\ninherit(StubArray, Array.prototype);\n// Weex proto freeze protection was here,\n// but it is unclear why the hack is need as MobX never changed the prototype\n// anyway, so removed it in V6\nvar LegacyObservableArray = /*#__PURE__*/function (_StubArray, _Symbol$toStringTag, _Symbol$iterator) {\n _inheritsLoose(LegacyObservableArray, _StubArray);\n function LegacyObservableArray(initialValues, enhancer, name, owned) {\n var _this;\n if (name === void 0) {\n name = process.env.NODE_ENV !== \"production\" ? \"ObservableArray@\" + getNextId() : \"ObservableArray\";\n }\n if (owned === void 0) {\n owned = false;\n }\n _this = _StubArray.call(this) || this;\n initObservable(function () {\n var adm = new ObservableArrayAdministration(name, enhancer, owned, true);\n adm.proxy_ = _assertThisInitialized(_this);\n addHiddenFinalProp(_assertThisInitialized(_this), $mobx, adm);\n if (initialValues && initialValues.length) {\n // @ts-ignore\n _this.spliceWithArray(0, 0, initialValues);\n }\n if (safariPrototypeSetterInheritanceBug) {\n // Seems that Safari won't use numeric prototype setter untill any * numeric property is\n // defined on the instance. After that it works fine, even if this property is deleted.\n Object.defineProperty(_assertThisInitialized(_this), \"0\", ENTRY_0);\n }\n });\n return _this;\n }\n var _proto = LegacyObservableArray.prototype;\n _proto.concat = function concat() {\n this[$mobx].atom_.reportObserved();\n for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) {\n arrays[_key] = arguments[_key];\n }\n return Array.prototype.concat.apply(this.slice(),\n //@ts-ignore\n arrays.map(function (a) {\n return isObservableArray(a) ? a.slice() : a;\n }));\n };\n _proto[_Symbol$iterator] = function () {\n var self = this;\n var nextIndex = 0;\n return makeIterable({\n next: function next() {\n return nextIndex < self.length ? {\n value: self[nextIndex++],\n done: false\n } : {\n done: true,\n value: undefined\n };\n }\n });\n };\n _createClass(LegacyObservableArray, [{\n key: \"length\",\n get: function get() {\n return this[$mobx].getArrayLength_();\n },\n set: function set(newLength) {\n this[$mobx].setArrayLength_(newLength);\n }\n }, {\n key: _Symbol$toStringTag,\n get: function get() {\n return \"Array\";\n }\n }]);\n return LegacyObservableArray;\n}(StubArray, Symbol.toStringTag, Symbol.iterator);\nObject.entries(arrayExtensions).forEach(function (_ref) {\n var prop = _ref[0],\n fn = _ref[1];\n if (prop !== \"concat\") {\n addHiddenProp(LegacyObservableArray.prototype, prop, fn);\n }\n});\nfunction createArrayEntryDescriptor(index) {\n return {\n enumerable: false,\n configurable: true,\n get: function get() {\n return this[$mobx].get_(index);\n },\n set: function set(value) {\n this[$mobx].set_(index, value);\n }\n };\n}\nfunction createArrayBufferItem(index) {\n defineProperty(LegacyObservableArray.prototype, \"\" + index, createArrayEntryDescriptor(index));\n}\nfunction reserveArrayBuffer(max) {\n if (max > OBSERVABLE_ARRAY_BUFFER_SIZE) {\n for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max + 100; index++) {\n createArrayBufferItem(index);\n }\n OBSERVABLE_ARRAY_BUFFER_SIZE = max;\n }\n}\nreserveArrayBuffer(1000);\nfunction createLegacyArray(initialValues, enhancer, name) {\n return new LegacyObservableArray(initialValues, enhancer, name);\n}\n\nfunction getAtom(thing, property) {\n if (typeof thing === \"object\" && thing !== null) {\n if (isObservableArray(thing)) {\n if (property !== undefined) {\n die(23);\n }\n return thing[$mobx].atom_;\n }\n if (isObservableSet(thing)) {\n return thing.atom_;\n }\n if (isObservableMap(thing)) {\n if (property === undefined) {\n return thing.keysAtom_;\n }\n var observable = thing.data_.get(property) || thing.hasMap_.get(property);\n if (!observable) {\n die(25, property, getDebugName(thing));\n }\n return observable;\n }\n if (isObservableObject(thing)) {\n if (!property) {\n return die(26);\n }\n var _observable = thing[$mobx].values_.get(property);\n if (!_observable) {\n die(27, property, getDebugName(thing));\n }\n return _observable;\n }\n if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {\n return thing;\n }\n } else if (isFunction(thing)) {\n if (isReaction(thing[$mobx])) {\n // disposer function\n return thing[$mobx];\n }\n }\n die(28);\n}\nfunction getAdministration(thing, property) {\n if (!thing) {\n die(29);\n }\n if (property !== undefined) {\n return getAdministration(getAtom(thing, property));\n }\n if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {\n return thing;\n }\n if (isObservableMap(thing) || isObservableSet(thing)) {\n return thing;\n }\n if (thing[$mobx]) {\n return thing[$mobx];\n }\n die(24, thing);\n}\nfunction getDebugName(thing, property) {\n var named;\n if (property !== undefined) {\n named = getAtom(thing, property);\n } else if (isAction(thing)) {\n return thing.name;\n } else if (isObservableObject(thing) || isObservableMap(thing) || isObservableSet(thing)) {\n named = getAdministration(thing);\n } else {\n // valid for arrays as well\n named = getAtom(thing);\n }\n return named.name_;\n}\n/**\n * Helper function for initializing observable structures, it applies:\n * 1. allowStateChanges so we don't violate enforceActions.\n * 2. untracked so we don't accidentaly subscribe to anything observable accessed during init in case the observable is created inside derivation.\n * 3. batch to avoid state version updates\n */\nfunction initObservable(cb) {\n var derivation = untrackedStart();\n var allowStateChanges = allowStateChangesStart(true);\n startBatch();\n try {\n return cb();\n } finally {\n endBatch();\n allowStateChangesEnd(allowStateChanges);\n untrackedEnd(derivation);\n }\n}\n\nvar toString = objectPrototype.toString;\nfunction deepEqual(a, b, depth) {\n if (depth === void 0) {\n depth = -1;\n }\n return eq(a, b, depth);\n}\n// Copied from https://github.com/jashkenas/underscore/blob/5c237a7c682fb68fd5378203f0bf22dce1624854/underscore.js#L1186-L1289\n// Internal recursive comparison function for `isEqual`.\nfunction eq(a, b, depth, aStack, bStack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).\n if (a === b) {\n return a !== 0 || 1 / a === 1 / b;\n }\n // `null` or `undefined` only equal to itself (strict comparison).\n if (a == null || b == null) {\n return false;\n }\n // `NaN`s are equivalent, but non-reflexive.\n if (a !== a) {\n return b !== b;\n }\n // Exhaust primitive checks\n var type = typeof a;\n if (type !== \"function\" && type !== \"object\" && typeof b != \"object\") {\n return false;\n }\n // Compare `[[Class]]` names.\n var className = toString.call(a);\n if (className !== toString.call(b)) {\n return false;\n }\n switch (className) {\n // Strings, numbers, regular expressions, dates, and booleans are compared by value.\n case \"[object RegExp]\":\n // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')\n case \"[object String]\":\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return \"\" + a === \"\" + b;\n case \"[object Number]\":\n // `NaN`s are equivalent, but non-reflexive.\n // Object(NaN) is equivalent to NaN.\n if (+a !== +a) {\n return +b !== +b;\n }\n // An `egal` comparison is performed for other numeric values.\n return +a === 0 ? 1 / +a === 1 / b : +a === +b;\n case \"[object Date]\":\n case \"[object Boolean]\":\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a === +b;\n case \"[object Symbol]\":\n return typeof Symbol !== \"undefined\" && Symbol.valueOf.call(a) === Symbol.valueOf.call(b);\n case \"[object Map]\":\n case \"[object Set]\":\n // Maps and Sets are unwrapped to arrays of entry-pairs, adding an incidental level.\n // Hide this extra level by increasing the depth.\n if (depth >= 0) {\n depth++;\n }\n break;\n }\n // Unwrap any wrapped objects.\n a = unwrap(a);\n b = unwrap(b);\n var areArrays = className === \"[object Array]\";\n if (!areArrays) {\n if (typeof a != \"object\" || typeof b != \"object\") {\n return false;\n }\n // Objects with different constructors are not equivalent, but `Object`s or `Array`s\n // from different frames are.\n var aCtor = a.constructor,\n bCtor = b.constructor;\n if (aCtor !== bCtor && !(isFunction(aCtor) && aCtor instanceof aCtor && isFunction(bCtor) && bCtor instanceof bCtor) && \"constructor\" in a && \"constructor\" in b) {\n return false;\n }\n }\n if (depth === 0) {\n return false;\n } else if (depth < 0) {\n depth = -1;\n }\n // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n // Initializing stack of traversed objects.\n // It's done here since we only need them for objects and arrays comparison.\n aStack = aStack || [];\n bStack = bStack || [];\n var length = aStack.length;\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (aStack[length] === a) {\n return bStack[length] === b;\n }\n }\n // Add the first object to the stack of traversed objects.\n aStack.push(a);\n bStack.push(b);\n // Recursively compare objects and arrays.\n if (areArrays) {\n // Compare array lengths to determine if a deep comparison is necessary.\n length = a.length;\n if (length !== b.length) {\n return false;\n }\n // Deep compare the contents, ignoring non-numeric properties.\n while (length--) {\n if (!eq(a[length], b[length], depth - 1, aStack, bStack)) {\n return false;\n }\n }\n } else {\n // Deep compare objects.\n var keys = Object.keys(a);\n var key;\n length = keys.length;\n // Ensure that both objects contain the same number of properties before comparing deep equality.\n if (Object.keys(b).length !== length) {\n return false;\n }\n while (length--) {\n // Deep compare each member\n key = keys[length];\n if (!(hasProp(b, key) && eq(a[key], b[key], depth - 1, aStack, bStack))) {\n return false;\n }\n }\n }\n // Remove the first object from the stack of traversed objects.\n aStack.pop();\n bStack.pop();\n return true;\n}\nfunction unwrap(a) {\n if (isObservableArray(a)) {\n return a.slice();\n }\n if (isES6Map(a) || isObservableMap(a)) {\n return Array.from(a.entries());\n }\n if (isES6Set(a) || isObservableSet(a)) {\n return Array.from(a.entries());\n }\n return a;\n}\n\nfunction makeIterable(iterator) {\n iterator[Symbol.iterator] = getSelf;\n return iterator;\n}\nfunction getSelf() {\n return this;\n}\n\nfunction isAnnotation(thing) {\n return (\n // Can be function\n thing instanceof Object && typeof thing.annotationType_ === \"string\" && isFunction(thing.make_) && isFunction(thing.extend_)\n );\n}\n\n/**\n * (c) Michel Weststrate 2015 - 2020\n * MIT Licensed\n *\n * Welcome to the mobx sources! To get a global overview of how MobX internally works,\n * this is a good place to start:\n * https://medium.com/@mweststrate/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254#.xvbh6qd74\n *\n * Source folders:\n * ===============\n *\n * - api/ Most of the public static methods exposed by the module can be found here.\n * - core/ Implementation of the MobX algorithm; atoms, derivations, reactions, dependency trees, optimizations. Cool stuff can be found here.\n * - types/ All the magic that is need to have observable objects, arrays and values is in this folder. Including the modifiers like `asFlat`.\n * - utils/ Utility stuff.\n *\n */\n[\"Symbol\", \"Map\", \"Set\"].forEach(function (m) {\n var g = getGlobal();\n if (typeof g[m] === \"undefined\") {\n die(\"MobX requires global '\" + m + \"' to be available or polyfilled\");\n }\n});\nif (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === \"object\") {\n // See: https://github.com/andykog/mobx-devtools/\n __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({\n spy: spy,\n extras: {\n getDebugName: getDebugName\n },\n $mobx: $mobx\n });\n}\n\nexport { $mobx, FlowCancellationError, ObservableMap, ObservableSet, Reaction, allowStateChanges as _allowStateChanges, runInAction as _allowStateChangesInsideComputed, allowStateReadsEnd as _allowStateReadsEnd, allowStateReadsStart as _allowStateReadsStart, autoAction as _autoAction, _endAction, getAdministration as _getAdministration, getGlobalState as _getGlobalState, interceptReads as _interceptReads, isComputingDerivation as _isComputingDerivation, resetGlobalState as _resetGlobalState, _startAction, action, autorun, comparer, computed, configure, createAtom, apiDefineProperty as defineProperty, entries, extendObservable, flow, flowResult, get, getAtom, getDebugName, getDependencyTree, getObserverTree, has, intercept, isAction, isObservableValue as isBoxedObservable, isComputed, isComputedProp, isFlow, isFlowCancellationError, isObservable, isObservableArray, isObservableMap, isObservableObject, isObservableProp, isObservableSet, keys, makeAutoObservable, makeObservable, observable, observe, onBecomeObserved, onBecomeUnobserved, onReactionError, override, apiOwnKeys as ownKeys, reaction, remove, runInAction, set, spy, toJS, trace, transaction, untracked, values, when };\n//# sourceMappingURL=mobx.esm.js.map\n","import { makeObservable } from \"mobx\";\nimport { useState } from \"react\";\nif (!useState) {\n throw new Error(\"mobx-react-lite requires React with Hooks support\");\n}\nif (!makeObservable) {\n throw new Error(\"mobx-react-lite@3 requires mobx at least version 6 to be available\");\n}\n//# sourceMappingURL=assertEnvironment.js.map","import { configure } from \"mobx\";\nexport function defaultNoopBatch(callback) {\n callback();\n}\nexport function observerBatching(reactionScheduler) {\n if (!reactionScheduler) {\n reactionScheduler = defaultNoopBatch;\n if (\"production\" !== process.env.NODE_ENV) {\n console.warn(\"[MobX] Failed to get unstable_batched updates from react-dom / react-native\");\n }\n }\n configure({ reactionScheduler: reactionScheduler });\n}\nexport var isObserverBatched = function () {\n if (\"production\" !== process.env.NODE_ENV) {\n console.warn(\"[MobX] Deprecated\");\n }\n return true;\n};\n//# sourceMappingURL=observerBatching.js.map","import { getDependencyTree } from \"mobx\";\nexport function printDebugValue(v) {\n return getDependencyTree(v);\n}\n//# sourceMappingURL=printDebugValue.js.map","export var REGISTRY_FINALIZE_AFTER = 10000;\nexport var REGISTRY_SWEEP_INTERVAL = 10000;\nvar TimerBasedFinalizationRegistry = /** @class */ (function () {\n function TimerBasedFinalizationRegistry(finalize) {\n var _this = this;\n Object.defineProperty(this, \"finalize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: finalize\n });\n Object.defineProperty(this, \"registrations\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Map()\n });\n Object.defineProperty(this, \"sweepTimeout\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // Bound so it can be used directly as setTimeout callback.\n Object.defineProperty(this, \"sweep\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: function (maxAge) {\n if (maxAge === void 0) { maxAge = REGISTRY_FINALIZE_AFTER; }\n // cancel timeout so we can force sweep anytime\n clearTimeout(_this.sweepTimeout);\n _this.sweepTimeout = undefined;\n var now = Date.now();\n _this.registrations.forEach(function (registration, token) {\n if (now - registration.registeredAt >= maxAge) {\n _this.finalize(registration.value);\n _this.registrations.delete(token);\n }\n });\n if (_this.registrations.size > 0) {\n _this.scheduleSweep();\n }\n }\n });\n // Bound so it can be exported directly as clearTimers test utility.\n Object.defineProperty(this, \"finalizeAllImmediately\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: function () {\n _this.sweep(0);\n }\n });\n }\n // Token is actually required with this impl\n Object.defineProperty(TimerBasedFinalizationRegistry.prototype, \"register\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (target, value, token) {\n this.registrations.set(token, {\n value: value,\n registeredAt: Date.now()\n });\n this.scheduleSweep();\n }\n });\n Object.defineProperty(TimerBasedFinalizationRegistry.prototype, \"unregister\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (token) {\n this.registrations.delete(token);\n }\n });\n Object.defineProperty(TimerBasedFinalizationRegistry.prototype, \"scheduleSweep\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n if (this.sweepTimeout === undefined) {\n this.sweepTimeout = setTimeout(this.sweep, REGISTRY_SWEEP_INTERVAL);\n }\n }\n });\n return TimerBasedFinalizationRegistry;\n}());\nexport { TimerBasedFinalizationRegistry };\nexport var UniversalFinalizationRegistry = typeof FinalizationRegistry !== \"undefined\"\n ? FinalizationRegistry\n : TimerBasedFinalizationRegistry;\n//# sourceMappingURL=UniversalFinalizationRegistry.js.map","import { UniversalFinalizationRegistry } from \"./UniversalFinalizationRegistry\";\nexport var observerFinalizationRegistry = new UniversalFinalizationRegistry(function (adm) {\n var _a;\n (_a = adm.reaction) === null || _a === void 0 ? void 0 : _a.dispose();\n adm.reaction = null;\n});\n//# sourceMappingURL=observerFinalizationRegistry.js.map","/**\n * @license React\n * use-sync-external-store-shim.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 e=require(\"react\");function h(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k=\"function\"===typeof Object.is?Object.is:h,l=e.useState,m=e.useEffect,n=e.useLayoutEffect,p=e.useDebugValue;function q(a,b){var d=b(),f=l({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n(function(){c.value=d;c.getSnapshot=b;r(c)&&g({inst:c})},[a,d,b]);m(function(){r(c)&&g({inst:c});return a(function(){r(c)&&g({inst:c})})},[a]);p(d);return d}\nfunction r(a){var b=a.getSnapshot;a=a.value;try{var d=b();return!k(a,d)}catch(f){return!0}}function t(a,b){return b()}var u=\"undefined\"===typeof window||\"undefined\"===typeof window.document||\"undefined\"===typeof window.document.createElement?t:q;exports.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim.production.min.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim.development.js');\n}\n","import { Reaction } from \"mobx\";\nimport React from \"react\";\nimport { printDebugValue } from \"./utils/printDebugValue\";\nimport { isUsingStaticRendering } from \"./staticRendering\";\nimport { observerFinalizationRegistry } from \"./utils/observerFinalizationRegistry\";\nimport { useSyncExternalStore } from \"use-sync-external-store/shim\";\n// Required by SSR when hydrating #3669\nvar getServerSnapshot = function () { };\nfunction createReaction(adm) {\n adm.reaction = new Reaction(\"observer\".concat(adm.name), function () {\n var _a;\n adm.stateVersion = Symbol();\n // onStoreChange won't be available until the component \"mounts\".\n // If state changes in between initial render and mount,\n // `useSyncExternalStore` should handle that by checking the state version and issuing update.\n (_a = adm.onStoreChange) === null || _a === void 0 ? void 0 : _a.call(adm);\n });\n}\nexport function useObserver(render, baseComponentName) {\n if (baseComponentName === void 0) { baseComponentName = \"observed\"; }\n if (isUsingStaticRendering()) {\n return render();\n }\n var admRef = React.useRef(null);\n if (!admRef.current) {\n // First render\n var adm_1 = {\n reaction: null,\n onStoreChange: null,\n stateVersion: Symbol(),\n name: baseComponentName,\n subscribe: function (onStoreChange) {\n // Do NOT access admRef here!\n observerFinalizationRegistry.unregister(adm_1);\n adm_1.onStoreChange = onStoreChange;\n if (!adm_1.reaction) {\n // We've lost our reaction and therefore all subscriptions, occurs when:\n // 1. Timer based finalization registry disposed reaction before component mounted.\n // 2. React \"re-mounts\" same component without calling render in between (typically ).\n // We have to recreate reaction and schedule re-render to recreate subscriptions,\n // even if state did not change.\n createReaction(adm_1);\n // `onStoreChange` won't force update if subsequent `getSnapshot` returns same value.\n // So we make sure that is not the case\n adm_1.stateVersion = Symbol();\n }\n return function () {\n var _a;\n // Do NOT access admRef here!\n adm_1.onStoreChange = null;\n (_a = adm_1.reaction) === null || _a === void 0 ? void 0 : _a.dispose();\n adm_1.reaction = null;\n };\n },\n getSnapshot: function () {\n // Do NOT access admRef here!\n return adm_1.stateVersion;\n }\n };\n admRef.current = adm_1;\n }\n var adm = admRef.current;\n if (!adm.reaction) {\n // First render or reaction was disposed by registry before subscribe\n createReaction(adm);\n // StrictMode/ConcurrentMode/Suspense may mean that our component is\n // rendered and abandoned multiple times, so we need to track leaked\n // Reactions.\n observerFinalizationRegistry.register(admRef, adm, adm);\n }\n React.useDebugValue(adm.reaction, printDebugValue);\n useSyncExternalStore(\n // Both of these must be stable, otherwise it would keep resubscribing every render.\n adm.subscribe, adm.getSnapshot, getServerSnapshot);\n // render the original component, but have the\n // reaction track the observables, so that rendering\n // can be invalidated (see above) once a dependency changes\n var renderResult;\n var exception;\n adm.reaction.track(function () {\n try {\n renderResult = render();\n }\n catch (e) {\n exception = e;\n }\n });\n if (exception) {\n throw exception; // re-throw any exceptions caught during rendering\n }\n return renderResult;\n}\n//# sourceMappingURL=useObserver.js.map","import { forwardRef, memo } from \"react\";\nimport { isUsingStaticRendering } from \"./staticRendering\";\nimport { useObserver } from \"./useObserver\";\nvar warnObserverOptionsDeprecated = true;\nvar hasSymbol = typeof Symbol === \"function\" && Symbol.for;\n// Using react-is had some issues (and operates on elements, not on types), see #608 / #609\nvar ReactForwardRefSymbol = hasSymbol\n ? Symbol.for(\"react.forward_ref\")\n : typeof forwardRef === \"function\" && forwardRef(function (props) { return null; })[\"$$typeof\"];\nvar ReactMemoSymbol = hasSymbol\n ? Symbol.for(\"react.memo\")\n : typeof memo === \"function\" && memo(function (props) { return null; })[\"$$typeof\"];\n// n.b. base case is not used for actual typings or exported in the typing files\nexport function observer(baseComponent, \n// TODO remove in next major\noptions) {\n var _a;\n if (process.env.NODE_ENV !== \"production\" && warnObserverOptionsDeprecated && options) {\n warnObserverOptionsDeprecated = false;\n console.warn(\"[mobx-react-lite] `observer(fn, { forwardRef: true })` is deprecated, use `observer(React.forwardRef(fn))`\");\n }\n if (ReactMemoSymbol && baseComponent[\"$$typeof\"] === ReactMemoSymbol) {\n throw new Error(\"[mobx-react-lite] You are trying to use `observer` on a function component wrapped in either another `observer` or `React.memo`. The observer already applies 'React.memo' for you.\");\n }\n // The working of observer is explained step by step in this talk: https://www.youtube.com/watch?v=cPF4iBedoF0&feature=youtu.be&t=1307\n if (isUsingStaticRendering()) {\n return baseComponent;\n }\n var useForwardRef = (_a = options === null || options === void 0 ? void 0 : options.forwardRef) !== null && _a !== void 0 ? _a : false;\n var render = baseComponent;\n var baseComponentName = baseComponent.displayName || baseComponent.name;\n // If already wrapped with forwardRef, unwrap,\n // so we can patch render and apply memo\n if (ReactForwardRefSymbol && baseComponent[\"$$typeof\"] === ReactForwardRefSymbol) {\n useForwardRef = true;\n render = baseComponent[\"render\"];\n if (typeof render !== \"function\") {\n throw new Error(\"[mobx-react-lite] `render` property of ForwardRef was not a function\");\n }\n }\n var observerComponent = function (props, ref) {\n return useObserver(function () { return render(props, ref); }, baseComponentName);\n };\n observerComponent.displayName = baseComponent.displayName;\n Object.defineProperty(observerComponent, \"name\", {\n value: baseComponent.name,\n writable: true,\n configurable: true\n });\n // Support legacy context: `contextTypes` must be applied before `memo`\n if (baseComponent.contextTypes) {\n ;\n observerComponent.contextTypes = baseComponent.contextTypes;\n }\n if (useForwardRef) {\n // `forwardRef` must be applied prior `memo`\n // `forwardRef(observer(cmp))` throws:\n // \"forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))\"\n observerComponent = forwardRef(observerComponent);\n }\n // memo; we are not interested in deep updates\n // in props; we assume that if deep objects are changed,\n // this is in observables, which would have been tracked anyway\n observerComponent = memo(observerComponent);\n copyStaticProperties(baseComponent, observerComponent);\n if (\"production\" !== process.env.NODE_ENV) {\n Object.defineProperty(observerComponent, \"contextTypes\", {\n set: function () {\n var _a, _b;\n throw new Error(\"[mobx-react-lite] `\".concat(this.displayName || ((_a = this.type) === null || _a === void 0 ? void 0 : _a.displayName) || ((_b = this.type) === null || _b === void 0 ? void 0 : _b.name) || \"Component\", \".contextTypes` must be set before applying `observer`.\"));\n }\n });\n }\n return observerComponent;\n}\n// based on https://github.com/mridgway/hoist-non-react-statics/blob/master/src/index.js\nvar hoistBlackList = {\n $$typeof: true,\n render: true,\n compare: true,\n type: true,\n // Don't redefine `displayName`,\n // it's defined as getter-setter pair on `memo` (see #3192).\n displayName: true\n};\nfunction copyStaticProperties(base, target) {\n Object.keys(base).forEach(function (key) {\n if (!hoistBlackList[key]) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(base, key));\n }\n });\n}\n//# sourceMappingURL=observer.js.map","var __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};\nimport { useDeprecated } from \"./utils/utils\";\nimport { observable, runInAction } from \"mobx\";\nimport { useState } from \"react\";\nexport function useAsObservableSource(current) {\n if (\"production\" !== process.env.NODE_ENV)\n useDeprecated(\"[mobx-react-lite] 'useAsObservableSource' is deprecated, please store the values directly in an observable, for example by using 'useLocalObservable', and sync future updates using 'useEffect' when needed. See the README for examples.\");\n var _a = __read(useState(function () { return observable(current, {}, { deep: false }); }), 1), res = _a[0];\n runInAction(function () {\n Object.assign(res, current);\n });\n return res;\n}\n//# sourceMappingURL=useAsObservableSource.js.map","var _a;\nimport \"./utils/assertEnvironment\";\nimport { unstable_batchedUpdates as batch } from \"./utils/reactBatchedUpdates\";\nimport { observerBatching } from \"./utils/observerBatching\";\nimport { useDeprecated } from \"./utils/utils\";\nimport { useObserver as useObserverOriginal } from \"./useObserver\";\nimport { enableStaticRendering } from \"./staticRendering\";\nimport { observerFinalizationRegistry } from \"./utils/observerFinalizationRegistry\";\nobserverBatching(batch);\nexport { isUsingStaticRendering, enableStaticRendering } from \"./staticRendering\";\nexport { observer } from \"./observer\";\nexport { Observer } from \"./ObserverComponent\";\nexport { useLocalObservable } from \"./useLocalObservable\";\nexport { useLocalStore } from \"./useLocalStore\";\nexport { useAsObservableSource } from \"./useAsObservableSource\";\nexport { observerFinalizationRegistry as _observerFinalizationRegistry };\nexport var clearTimers = (_a = observerFinalizationRegistry[\"finalizeAllImmediately\"]) !== null && _a !== void 0 ? _a : (function () { });\nexport function useObserver(fn, baseComponentName) {\n if (baseComponentName === void 0) { baseComponentName = \"observed\"; }\n if (\"production\" !== process.env.NODE_ENV) {\n useDeprecated(\"[mobx-react-lite] 'useObserver(fn)' is deprecated. Use `{fn}` instead, or wrap the entire component in `observer`.\");\n }\n return useObserverOriginal(fn, baseComponentName);\n}\nexport { isObserverBatched, observerBatching } from \"./utils/observerBatching\";\nexport function useStaticRendering(enable) {\n if (\"production\" !== process.env.NODE_ENV) {\n console.warn(\"[mobx-react-lite] 'useStaticRendering' is deprecated, use 'enableStaticRendering' instead\");\n }\n enableStaticRendering(enable);\n}\n//# sourceMappingURL=index.js.map","export const log = (...args: any[]) => {\n if (!window.pyneSettings?.debug) return;\n console.log(\"PYNE:\", ...args);\n};\n\nexport const debugLog = (...args: any[]) => {\n if (!window.pyneSettings?.debug) return;\n console.log(\"%cPYNE DEBUG:\", \"color: blue;\", ...args);\n};\n","import { PingResponse } from \"@common/api/ping\";\n\nconst CACHE_BUSTING_HEADERS = {\n \"Cache-Control\": \"no-cache, no-store, must-revalidate, max-age=0\",\n Pragma: \"no-cache\",\n Expires: \"0\",\n} as const;\n\nexport interface PingApiArgs {\n appId: string;\n apiBaseUrl: string;\n userData: Record;\n previewGuideId?: string;\n activeGuideId?: string;\n activeTourPlaybackVersion?: string;\n requestId: number;\n}\n\nexport async function fetchPing({\n appId,\n apiBaseUrl,\n requestId,\n userData,\n previewGuideId,\n activeGuideId,\n activeTourPlaybackVersion,\n}: PingApiArgs) {\n function encodeUserData(data: Record) {\n const newData = { ...data };\n for (const [key, value] of Object.entries(newData)) {\n if (value === undefined) {\n newData[key] = \"__unset__\";\n }\n }\n return newData;\n }\n\n const payload = {\n app_id: appId,\n user_data: userData?.id ? encodeUserData(userData) : undefined,\n previewGuideId,\n activeGuideId,\n activeTourPlaybackVersion,\n };\n\n const res = await fetch(`${apiBaseUrl}/widget/ping`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Pyne-Request-Id\": requestId.toString(),\n ...(previewGuideId ? CACHE_BUSTING_HEADERS : {}),\n },\n body: JSON.stringify(payload),\n });\n\n const data = (await res.json()) as PingResponse;\n const allGuides = data.allGuides;\n const userState = data.userState as Record;\n const debugData = data.debug as any | undefined;\n\n return { userState, allGuides, debugData };\n}\n","import { makeObservable, observable } from \"mobx\";\nimport { log } from \"@/lib/log\";\nimport type { RootStore } from \"@/store\";\nimport { PingResponse } from \"@common/api/ping\";\nimport { fetchPing, PingApiArgs } from \"../api/ping\";\nimport { GuideRegistry } from \"@/stores/GuideRegistry\";\n\ntype SyncGuidesArgs = Omit;\n\ntype SyncGuidesRequest = {\n args: SyncGuidesArgs;\n resolve: (guides: SyncResult | undefined) => void;\n reject: (reason?: any) => void;\n};\n\nexport type SyncResult = {\n allGuides: PingResponse[\"allGuides\"];\n userState: Record;\n debugData: PingResponse[\"debug\"];\n};\n\ninterface PyneClient {\n currentUserData: Record;\n}\n\nexport interface SyncManagerParams {\n rootStore: RootStore;\n pyneClient: PyneClient;\n guideRegistry: GuideRegistry;\n}\n\nexport class SyncManager {\n rootStore: RootStore;\n guideRegistry: GuideRegistry;\n private _syncMeta?: { lastArguments: any; lastFetch: number };\n\n requestQueue: SyncGuidesRequest[] = [];\n processingQueue = false; // Track if a request is being processed\n private _currentRequestId = 0;\n private pyneClient: PyneClient;\n private lastUserState: Record = {};\n private lastDebugData: PingResponse[\"debug\"];\n\n // For easy mocking\n fetchPing = fetchPing;\n\n constructor({ rootStore, pyneClient, guideRegistry }: SyncManagerParams) {\n makeObservable(this, {\n requestQueue: observable.ref,\n processingQueue: observable.ref,\n });\n this.rootStore = rootStore;\n this.pyneClient = pyneClient;\n this.guideRegistry = guideRegistry;\n }\n\n get pyneSettings() {\n return this.rootStore.pyneSettings;\n }\n\n get isSettled() {\n return !this.processingQueue && this.requestQueue.length === 0;\n }\n\n /**\n * Queue and process the sync guides request\n */\n async syncGuides({\n previewGuideId,\n activeGuideId,\n tourPlaybackVersion,\n }: {\n previewGuideId?: string;\n activeGuideId?: string;\n tourPlaybackVersion?: string;\n }): Promise {\n log(\"syncGuides called\");\n const userData = this.pyneClient.currentUserData;\n return new Promise((resolve, reject) => {\n this._currentRequestId++;\n this.requestQueue.push({\n args: {\n requestId: this._currentRequestId,\n userData,\n previewGuideId,\n activeGuideId,\n activeTourPlaybackVersion: tourPlaybackVersion,\n },\n resolve,\n reject,\n });\n this.processNextRequest();\n });\n }\n\n /**\n * Process the next request in the queue\n */\n private async processNextRequest() {\n if (this.processingQueue || this.requestQueue.length === 0) {\n return; // Already processing or queue is empty\n }\n\n this.processingQueue = true;\n\n const { args, resolve, reject } = this.requestQueue.shift()!;\n\n try {\n const syncMeta = {\n lastArguments: args.userData,\n lastFetch: Date.now(),\n };\n\n const isSamePayload = JSON.stringify(this._syncMeta?.lastArguments) === JSON.stringify(syncMeta.lastArguments);\n const isStale = this._syncMeta?.lastFetch && Date.now() - this._syncMeta.lastFetch > 1000 * 10; // 10 seconds\n if (isSamePayload && !isStale) {\n log(\"sync skipped\");\n resolve({ userState: this.lastUserState, allGuides: this.guideRegistry.guides, debugData: this.lastDebugData });\n } else {\n this._syncMeta = syncMeta;\n log(\"syncing\");\n\n if (!(this.pyneSettings.app_id && this.pyneSettings.api_base)) {\n throw new Error(\"Pyne settings not found\");\n }\n\n const result = await this.fetchPing({\n appId: this.pyneSettings.app_id,\n apiBaseUrl: this.pyneSettings.api_base,\n ...args,\n });\n\n this.lastUserState = result.userState;\n this.lastDebugData = result.debugData;\n this.guideRegistry.setGuides(result.allGuides);\n\n resolve(result);\n }\n } catch (error) {\n reject(error);\n } finally {\n this.processingQueue = false;\n this.processNextRequest();\n }\n }\n}\n","export default function(n){return{all:n=n||new Map,on:function(t,e){var i=n.get(t);i?i.push(e):n.set(t,[e])},off:function(t,e){var i=n.get(t);i&&(e?i.splice(i.indexOf(e)>>>0,1):n.set(t,[]))},emit:function(t,e){var i=n.get(t);i&&i.slice().map(function(n){n(e)}),(i=n.get(\"*\"))&&i.slice().map(function(n){n(t,e)})}}}\n//# sourceMappingURL=mitt.mjs.map\n","import mitt, { Emitter, Handler, WildcardHandler } from \"mitt\";\nimport { EventsWithContext } from \"./types\";\n\ntype Middleware = (context: Context, type: EventType) => Context;\n\nexport class BaseEventEmitter, Context = any> {\n protected emitter: Emitter>;\n private middlewares: { [Key in keyof Events | \"*\"]?: Middleware[] } = {};\n\n constructor() {\n this.emitter = mitt>();\n }\n\n use(\n type: Key,\n middleware: Middleware\n ): () => void {\n if (!this.middlewares[type]) {\n this.middlewares[type] = [];\n }\n this.middlewares[type]!.push(middleware);\n\n return () => {\n this.middlewares[type] = this.middlewares[type]!.filter((mw) => mw !== middleware);\n };\n }\n\n on(\n type: Key,\n handler: Key extends \"*\"\n ? WildcardHandler>\n : Handler[Extract]>\n ) {\n this.emitter.on(type as any, handler as any);\n\n return () => {\n this.emitter.off(type as any, handler as any);\n };\n }\n\n off(\n type: Key,\n handler: Key extends \"*\"\n ? WildcardHandler>\n : Handler[Extract]>\n ): void {\n this.emitter.off(type as any, handler as any);\n }\n\n emit(\n type: Key,\n eventData: Events[Key],\n context?: Context\n ): EventsWithContext[Key] {\n let ctx = context || ({} as Context);\n\n const globalMiddlewares = this.middlewares[\"*\"] || [];\n globalMiddlewares.forEach((middleware) => {\n ctx = middleware(ctx, type as string);\n });\n\n const eventMiddlewares = this.middlewares[type] || [];\n eventMiddlewares.forEach((middleware) => {\n ctx = middleware(ctx, type);\n });\n\n const dataWithContext = { context: ctx, payload: eventData };\n\n this.emitter.emit(type as any, dataWithContext);\n\n return dataWithContext;\n }\n}\n","import { Handler, WildcardHandler } from \"mitt\";\nimport { BaseEventEmitter } from \"./baseEventEmitter\";\nimport { AllEvents, AllContexts } from \"./allEvents\";\nimport { EventsWithContext } from \"./types\";\n\nexport class GlobalEventBus extends BaseEventEmitter {\n private static instance: GlobalEventBus;\n\n private constructor() {\n super();\n }\n\n static getInstance() {\n if (!GlobalEventBus.instance) {\n GlobalEventBus.instance = new GlobalEventBus();\n }\n\n return GlobalEventBus.instance;\n }\n\n on(\n type: Key,\n handler: Key extends \"*\"\n ? WildcardHandler>\n : Handler[Extract]>\n ) {\n return super.on(type, handler);\n }\n\n off(\n type: Key,\n handler: Key extends \"*\"\n ? WildcardHandler>\n : Handler[Extract]>\n ) {\n return super.off(type, handler);\n }\n\n static resetInstance() {\n GlobalEventBus.instance = new GlobalEventBus();\n return GlobalEventBus.instance;\n }\n}\n\nexport let globalEventBus = GlobalEventBus.getInstance();\n\nexport function resetGlobalEventBus() {\n globalEventBus = GlobalEventBus.resetInstance();\n}\n","/**\n * Register event listener on document that fires when:\n * * tab change or tab close (in mobile or desktop)\n * * click back / forward button\n * * click any link or perform any other navigation action\n * * soft refresh / hard refresh\n **/\nexport function onPageChange(cb: () => void) {\n document.addEventListener(\"visibilitychange\", () => {\n if (document.visibilityState === \"hidden\") {\n cb();\n }\n });\n\n window.addEventListener(\"beforeunload\", cb);\n}\n","import { onPageChange } from \"./onPageChange\";\n\ntype TrackingEvent = {};\n\nexport class EventBuffer {\n private buffer: TrackingEvent[] = [];\n private isSending = false;\n private lastFlush = 0;\n private flushTimeoutId: number | undefined;\n\n // Max waiting time before sending the batch\n private batchTimeout = 5000;\n\n // Max number of events to send in a batch\n private batchSize = 10;\n\n private apiBaseUrl: string;\n private appId: string;\n\n constructor(apiBaseUrl: string, appId: string) {\n this.apiBaseUrl = apiBaseUrl;\n this.appId = appId;\n onPageChange(() => this.flush());\n }\n\n push(event: TrackingEvent) {\n this.buffer.push(event);\n this.scheduleFlush();\n }\n\n async scheduleFlush() {\n const reachedSizeThreshold = this.buffer.length >= this.batchSize;\n const reachedTimeout = this.lastFlush + this.batchTimeout < Date.now();\n\n if (reachedSizeThreshold || reachedTimeout) {\n this.flush();\n return;\n }\n\n if (!this.flushTimeoutId) {\n this.flushTimeoutId = setTimeout(() => this.flush(), this.batchTimeout) as any;\n }\n }\n\n async flush() {\n if (this.flushTimeoutId) {\n clearTimeout(this.flushTimeoutId);\n this.flushTimeoutId = undefined;\n }\n\n if (this.isSending) return;\n if (this.buffer.length === 0) return;\n\n this.isSending = true;\n this.lastFlush = Date.now();\n\n const events = this.buffer.splice(0);\n this.sendBatch(events);\n\n this.isSending = false;\n }\n\n sendBatch(events: TrackingEvent[]) {\n navigator.sendBeacon(`${this.apiBaseUrl ?? \"\"}/widget/track`, JSON.stringify({ events, app_id: this.appId }));\n }\n}\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(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)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(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}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(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}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n function next() {\n while (env.stack.length) {\n var rec = env.stack.pop();\n try {\n var result = rec.dispose && rec.dispose.call(rec.value);\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n catch (e) {\n fail(e);\n }\n }\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n};\n","import { __extends } from \"tslib\";\nvar genericMessage = \"Invariant Violation\";\nvar _a = Object.setPrototypeOf, setPrototypeOf = _a === void 0 ? function (obj, proto) {\n obj.__proto__ = proto;\n return obj;\n} : _a;\nvar InvariantError = /** @class */ (function (_super) {\n __extends(InvariantError, _super);\n function InvariantError(message) {\n if (message === void 0) { message = genericMessage; }\n var _this = _super.call(this, typeof message === \"number\"\n ? genericMessage + \": \" + message + \" (see https://github.com/apollographql/invariant-packages)\"\n : message) || this;\n _this.framesToPop = 1;\n _this.name = genericMessage;\n setPrototypeOf(_this, InvariantError.prototype);\n return _this;\n }\n return InvariantError;\n}(Error));\nexport { InvariantError };\nexport function invariant(condition, message) {\n if (!condition) {\n throw new InvariantError(message);\n }\n}\nvar verbosityLevels = [\"debug\", \"log\", \"warn\", \"error\", \"silent\"];\nvar verbosityLevel = verbosityLevels.indexOf(\"log\");\nfunction wrapConsoleMethod(name) {\n return function () {\n if (verbosityLevels.indexOf(name) >= verbosityLevel) {\n // Default to console.log if this host environment happens not to provide\n // all the console.* methods we need.\n var method = console[name] || console.log;\n return method.apply(console, arguments);\n }\n };\n}\n(function (invariant) {\n invariant.debug = wrapConsoleMethod(\"debug\");\n invariant.log = wrapConsoleMethod(\"log\");\n invariant.warn = wrapConsoleMethod(\"warn\");\n invariant.error = wrapConsoleMethod(\"error\");\n})(invariant || (invariant = {}));\nexport function setVerbosity(level) {\n var old = verbosityLevels[verbosityLevel];\n verbosityLevel = Math.max(0, verbosityLevels.indexOf(level));\n return old;\n}\nexport default invariant;\n//# sourceMappingURL=invariant.js.map","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e))for(t=0;t (lukeed.com)\n */\nfunction twJoin() {\n var index = 0;\n var argument;\n var resolvedValue;\n var string = '';\n while (index < arguments.length) {\n if (argument = arguments[index++]) {\n if (resolvedValue = toValue(argument)) {\n string && (string += ' ');\n string += resolvedValue;\n }\n }\n }\n return string;\n}\nfunction toValue(mix) {\n if (typeof mix === 'string') {\n return mix;\n }\n var resolvedValue;\n var string = '';\n for (var k = 0; k < mix.length; k++) {\n if (mix[k]) {\n if (resolvedValue = toValue(mix[k])) {\n string && (string += ' ');\n string += resolvedValue;\n }\n }\n }\n return string;\n}\n\nexport { twJoin };\n//# sourceMappingURL=tw-join.mjs.map\n","var CLASS_PART_SEPARATOR = '-';\nfunction createClassUtils(config) {\n var classMap = createClassMap(config);\n var conflictingClassGroups = config.conflictingClassGroups,\n _config$conflictingCl = config.conflictingClassGroupModifiers,\n conflictingClassGroupModifiers = _config$conflictingCl === void 0 ? {} : _config$conflictingCl;\n function getClassGroupId(className) {\n var classParts = className.split(CLASS_PART_SEPARATOR);\n // Classes like `-inset-1` produce an empty string as first classPart. We assume that classes for negative values are used correctly and remove it from classParts.\n if (classParts[0] === '' && classParts.length !== 1) {\n classParts.shift();\n }\n return getGroupRecursive(classParts, classMap) || getGroupIdForArbitraryProperty(className);\n }\n function getConflictingClassGroupIds(classGroupId, hasPostfixModifier) {\n var conflicts = conflictingClassGroups[classGroupId] || [];\n if (hasPostfixModifier && conflictingClassGroupModifiers[classGroupId]) {\n return [].concat(conflicts, conflictingClassGroupModifiers[classGroupId]);\n }\n return conflicts;\n }\n return {\n getClassGroupId: getClassGroupId,\n getConflictingClassGroupIds: getConflictingClassGroupIds\n };\n}\nfunction getGroupRecursive(classParts, classPartObject) {\n if (classParts.length === 0) {\n return classPartObject.classGroupId;\n }\n var currentClassPart = classParts[0];\n var nextClassPartObject = classPartObject.nextPart.get(currentClassPart);\n var classGroupFromNextClassPart = nextClassPartObject ? getGroupRecursive(classParts.slice(1), nextClassPartObject) : undefined;\n if (classGroupFromNextClassPart) {\n return classGroupFromNextClassPart;\n }\n if (classPartObject.validators.length === 0) {\n return undefined;\n }\n var classRest = classParts.join(CLASS_PART_SEPARATOR);\n return classPartObject.validators.find(function (_ref) {\n var validator = _ref.validator;\n return validator(classRest);\n })?.classGroupId;\n}\nvar arbitraryPropertyRegex = /^\\[(.+)\\]$/;\nfunction getGroupIdForArbitraryProperty(className) {\n if (arbitraryPropertyRegex.test(className)) {\n var arbitraryPropertyClassName = arbitraryPropertyRegex.exec(className)[1];\n var property = arbitraryPropertyClassName?.substring(0, arbitraryPropertyClassName.indexOf(':'));\n if (property) {\n // I use two dots here because one dot is used as prefix for class groups in plugins\n return 'arbitrary..' + property;\n }\n }\n}\n/**\n * Exported for testing only\n */\nfunction createClassMap(config) {\n var theme = config.theme,\n prefix = config.prefix;\n var classMap = {\n nextPart: new Map(),\n validators: []\n };\n var prefixedClassGroupEntries = getPrefixedClassGroupEntries(Object.entries(config.classGroups), prefix);\n prefixedClassGroupEntries.forEach(function (_ref2) {\n var classGroupId = _ref2[0],\n classGroup = _ref2[1];\n processClassesRecursively(classGroup, classMap, classGroupId, theme);\n });\n return classMap;\n}\nfunction processClassesRecursively(classGroup, classPartObject, classGroupId, theme) {\n classGroup.forEach(function (classDefinition) {\n if (typeof classDefinition === 'string') {\n var classPartObjectToEdit = classDefinition === '' ? classPartObject : getPart(classPartObject, classDefinition);\n classPartObjectToEdit.classGroupId = classGroupId;\n return;\n }\n if (typeof classDefinition === 'function') {\n if (isThemeGetter(classDefinition)) {\n processClassesRecursively(classDefinition(theme), classPartObject, classGroupId, theme);\n return;\n }\n classPartObject.validators.push({\n validator: classDefinition,\n classGroupId: classGroupId\n });\n return;\n }\n Object.entries(classDefinition).forEach(function (_ref3) {\n var key = _ref3[0],\n classGroup = _ref3[1];\n processClassesRecursively(classGroup, getPart(classPartObject, key), classGroupId, theme);\n });\n });\n}\nfunction getPart(classPartObject, path) {\n var currentClassPartObject = classPartObject;\n path.split(CLASS_PART_SEPARATOR).forEach(function (pathPart) {\n if (!currentClassPartObject.nextPart.has(pathPart)) {\n currentClassPartObject.nextPart.set(pathPart, {\n nextPart: new Map(),\n validators: []\n });\n }\n currentClassPartObject = currentClassPartObject.nextPart.get(pathPart);\n });\n return currentClassPartObject;\n}\nfunction isThemeGetter(func) {\n return func.isThemeGetter;\n}\nfunction getPrefixedClassGroupEntries(classGroupEntries, prefix) {\n if (!prefix) {\n return classGroupEntries;\n }\n return classGroupEntries.map(function (_ref4) {\n var classGroupId = _ref4[0],\n classGroup = _ref4[1];\n var prefixedClassGroup = classGroup.map(function (classDefinition) {\n if (typeof classDefinition === 'string') {\n return prefix + classDefinition;\n }\n if (typeof classDefinition === 'object') {\n return Object.fromEntries(Object.entries(classDefinition).map(function (_ref5) {\n var key = _ref5[0],\n value = _ref5[1];\n return [prefix + key, value];\n }));\n }\n return classDefinition;\n });\n return [classGroupId, prefixedClassGroup];\n });\n}\n\nexport { createClassMap, createClassUtils };\n//# sourceMappingURL=class-utils.mjs.map\n","// LRU cache inspired from hashlru (https://github.com/dominictarr/hashlru/blob/v1.0.4/index.js) but object replaced with Map to improve performance\nfunction createLruCache(maxCacheSize) {\n if (maxCacheSize < 1) {\n return {\n get: function get() {\n return undefined;\n },\n set: function set() {}\n };\n }\n var cacheSize = 0;\n var cache = new Map();\n var previousCache = new Map();\n function update(key, value) {\n cache.set(key, value);\n cacheSize++;\n if (cacheSize > maxCacheSize) {\n cacheSize = 0;\n previousCache = cache;\n cache = new Map();\n }\n }\n return {\n get: function get(key) {\n var value = cache.get(key);\n if (value !== undefined) {\n return value;\n }\n if ((value = previousCache.get(key)) !== undefined) {\n update(key, value);\n return value;\n }\n },\n set: function set(key, value) {\n if (cache.has(key)) {\n cache.set(key, value);\n } else {\n update(key, value);\n }\n }\n };\n}\n\nexport { createLruCache };\n//# sourceMappingURL=lru-cache.mjs.map\n","var IMPORTANT_MODIFIER = '!';\nfunction createSplitModifiers(config) {\n var separator = config.separator || ':';\n var isSeparatorSingleCharacter = separator.length === 1;\n var firstSeparatorCharacter = separator[0];\n var separatorLength = separator.length;\n // splitModifiers inspired by https://github.com/tailwindlabs/tailwindcss/blob/v3.2.2/src/util/splitAtTopLevelOnly.js\n return function splitModifiers(className) {\n var modifiers = [];\n var bracketDepth = 0;\n var modifierStart = 0;\n var postfixModifierPosition;\n for (var index = 0; index < className.length; index++) {\n var currentCharacter = className[index];\n if (bracketDepth === 0) {\n if (currentCharacter === firstSeparatorCharacter && (isSeparatorSingleCharacter || className.slice(index, index + separatorLength) === separator)) {\n modifiers.push(className.slice(modifierStart, index));\n modifierStart = index + separatorLength;\n continue;\n }\n if (currentCharacter === '/') {\n postfixModifierPosition = index;\n continue;\n }\n }\n if (currentCharacter === '[') {\n bracketDepth++;\n } else if (currentCharacter === ']') {\n bracketDepth--;\n }\n }\n var baseClassNameWithImportantModifier = modifiers.length === 0 ? className : className.substring(modifierStart);\n var hasImportantModifier = baseClassNameWithImportantModifier.startsWith(IMPORTANT_MODIFIER);\n var baseClassName = hasImportantModifier ? baseClassNameWithImportantModifier.substring(1) : baseClassNameWithImportantModifier;\n var maybePostfixModifierPosition = postfixModifierPosition && postfixModifierPosition > modifierStart ? postfixModifierPosition - modifierStart : undefined;\n return {\n modifiers: modifiers,\n hasImportantModifier: hasImportantModifier,\n baseClassName: baseClassName,\n maybePostfixModifierPosition: maybePostfixModifierPosition\n };\n };\n}\n/**\n * Sorts modifiers according to following schema:\n * - Predefined modifiers are sorted alphabetically\n * - When an arbitrary variant appears, it must be preserved which modifiers are before and after it\n */\nfunction sortModifiers(modifiers) {\n if (modifiers.length <= 1) {\n return modifiers;\n }\n var sortedModifiers = [];\n var unsortedModifiers = [];\n modifiers.forEach(function (modifier) {\n var isArbitraryVariant = modifier[0] === '[';\n if (isArbitraryVariant) {\n sortedModifiers.push.apply(sortedModifiers, unsortedModifiers.sort().concat([modifier]));\n unsortedModifiers = [];\n } else {\n unsortedModifiers.push(modifier);\n }\n });\n sortedModifiers.push.apply(sortedModifiers, unsortedModifiers.sort());\n return sortedModifiers;\n}\n\nexport { IMPORTANT_MODIFIER, createSplitModifiers, sortModifiers };\n//# sourceMappingURL=modifier-utils.mjs.map\n","import { createClassUtils } from './class-utils.mjs';\nimport { createLruCache } from './lru-cache.mjs';\nimport { createSplitModifiers } from './modifier-utils.mjs';\n\nfunction createConfigUtils(config) {\n return {\n cache: createLruCache(config.cacheSize),\n splitModifiers: createSplitModifiers(config),\n ...createClassUtils(config)\n };\n}\n\nexport { createConfigUtils };\n//# sourceMappingURL=config-utils.mjs.map\n","import { sortModifiers, IMPORTANT_MODIFIER } from './modifier-utils.mjs';\n\nvar SPLIT_CLASSES_REGEX = /\\s+/;\nfunction mergeClassList(classList, configUtils) {\n var splitModifiers = configUtils.splitModifiers,\n getClassGroupId = configUtils.getClassGroupId,\n getConflictingClassGroupIds = configUtils.getConflictingClassGroupIds;\n /**\n * Set of classGroupIds in following format:\n * `{importantModifier}{variantModifiers}{classGroupId}`\n * @example 'float'\n * @example 'hover:focus:bg-color'\n * @example 'md:!pr'\n */\n var classGroupsInConflict = new Set();\n return classList.trim().split(SPLIT_CLASSES_REGEX).map(function (originalClassName) {\n var _splitModifiers = splitModifiers(originalClassName),\n modifiers = _splitModifiers.modifiers,\n hasImportantModifier = _splitModifiers.hasImportantModifier,\n baseClassName = _splitModifiers.baseClassName,\n maybePostfixModifierPosition = _splitModifiers.maybePostfixModifierPosition;\n var classGroupId = getClassGroupId(maybePostfixModifierPosition ? baseClassName.substring(0, maybePostfixModifierPosition) : baseClassName);\n var hasPostfixModifier = Boolean(maybePostfixModifierPosition);\n if (!classGroupId) {\n if (!maybePostfixModifierPosition) {\n return {\n isTailwindClass: false,\n originalClassName: originalClassName\n };\n }\n classGroupId = getClassGroupId(baseClassName);\n if (!classGroupId) {\n return {\n isTailwindClass: false,\n originalClassName: originalClassName\n };\n }\n hasPostfixModifier = false;\n }\n var variantModifier = sortModifiers(modifiers).join(':');\n var modifierId = hasImportantModifier ? variantModifier + IMPORTANT_MODIFIER : variantModifier;\n return {\n isTailwindClass: true,\n modifierId: modifierId,\n classGroupId: classGroupId,\n originalClassName: originalClassName,\n hasPostfixModifier: hasPostfixModifier\n };\n }).reverse()\n // Last class in conflict wins, so we need to filter conflicting classes in reverse order.\n .filter(function (parsed) {\n if (!parsed.isTailwindClass) {\n return true;\n }\n var modifierId = parsed.modifierId,\n classGroupId = parsed.classGroupId,\n hasPostfixModifier = parsed.hasPostfixModifier;\n var classId = modifierId + classGroupId;\n if (classGroupsInConflict.has(classId)) {\n return false;\n }\n classGroupsInConflict.add(classId);\n getConflictingClassGroupIds(classGroupId, hasPostfixModifier).forEach(function (group) {\n return classGroupsInConflict.add(modifierId + group);\n });\n return true;\n }).reverse().map(function (parsed) {\n return parsed.originalClassName;\n }).join(' ');\n}\n\nexport { mergeClassList };\n//# sourceMappingURL=merge-classlist.mjs.map\n","import { createConfigUtils } from './config-utils.mjs';\nimport { mergeClassList } from './merge-classlist.mjs';\nimport { twJoin } from './tw-join.mjs';\n\nfunction createTailwindMerge() {\n for (var _len = arguments.length, createConfig = new Array(_len), _key = 0; _key < _len; _key++) {\n createConfig[_key] = arguments[_key];\n }\n var configUtils;\n var cacheGet;\n var cacheSet;\n var functionToCall = initTailwindMerge;\n function initTailwindMerge(classList) {\n var firstCreateConfig = createConfig[0],\n restCreateConfig = createConfig.slice(1);\n var config = restCreateConfig.reduce(function (previousConfig, createConfigCurrent) {\n return createConfigCurrent(previousConfig);\n }, firstCreateConfig());\n configUtils = createConfigUtils(config);\n cacheGet = configUtils.cache.get;\n cacheSet = configUtils.cache.set;\n functionToCall = tailwindMerge;\n return tailwindMerge(classList);\n }\n function tailwindMerge(classList) {\n var cachedResult = cacheGet(classList);\n if (cachedResult) {\n return cachedResult;\n }\n var result = mergeClassList(classList, configUtils);\n cacheSet(classList, result);\n return result;\n }\n return function callTailwindMerge() {\n return functionToCall(twJoin.apply(null, arguments));\n };\n}\n\nexport { createTailwindMerge };\n//# sourceMappingURL=create-tailwind-merge.mjs.map\n","function fromTheme(key) {\n var themeGetter = function themeGetter(theme) {\n return theme[key] || [];\n };\n themeGetter.isThemeGetter = true;\n return themeGetter;\n}\n\nexport { fromTheme };\n//# sourceMappingURL=from-theme.mjs.map\n","var arbitraryValueRegex = /^\\[(?:([a-z-]+):)?(.+)\\]$/i;\nvar fractionRegex = /^\\d+\\/\\d+$/;\nvar stringLengths = /*#__PURE__*/new Set(['px', 'full', 'screen']);\nvar tshirtUnitRegex = /^(\\d+(\\.\\d+)?)?(xs|sm|md|lg|xl)$/;\nvar lengthUnitRegex = /\\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\\b(calc|min|max|clamp)\\(.+\\)|^0$/;\n// Shadow always begins with x and y offset separated by underscore\nvar shadowRegex = /^-?((\\d+)?\\.?(\\d+)[a-z]+|0)_-?((\\d+)?\\.?(\\d+)[a-z]+|0)/;\nfunction isLength(value) {\n return isNumber(value) || stringLengths.has(value) || fractionRegex.test(value) || isArbitraryLength(value);\n}\nfunction isArbitraryLength(value) {\n return getIsArbitraryValue(value, 'length', isLengthOnly);\n}\nfunction isArbitrarySize(value) {\n return getIsArbitraryValue(value, 'size', isNever);\n}\nfunction isArbitraryPosition(value) {\n return getIsArbitraryValue(value, 'position', isNever);\n}\nfunction isArbitraryUrl(value) {\n return getIsArbitraryValue(value, 'url', isUrl);\n}\nfunction isArbitraryNumber(value) {\n return getIsArbitraryValue(value, 'number', isNumber);\n}\n/**\n * @deprecated Will be removed in next major version. Use `isArbitraryNumber` instead.\n */\nvar isArbitraryWeight = isArbitraryNumber;\nfunction isNumber(value) {\n return !Number.isNaN(Number(value));\n}\nfunction isPercent(value) {\n return value.endsWith('%') && isNumber(value.slice(0, -1));\n}\nfunction isInteger(value) {\n return isIntegerOnly(value) || getIsArbitraryValue(value, 'number', isIntegerOnly);\n}\nfunction isArbitraryValue(value) {\n return arbitraryValueRegex.test(value);\n}\nfunction isAny() {\n return true;\n}\nfunction isTshirtSize(value) {\n return tshirtUnitRegex.test(value);\n}\nfunction isArbitraryShadow(value) {\n return getIsArbitraryValue(value, '', isShadow);\n}\nfunction getIsArbitraryValue(value, label, testValue) {\n var result = arbitraryValueRegex.exec(value);\n if (result) {\n if (result[1]) {\n return result[1] === label;\n }\n return testValue(result[2]);\n }\n return false;\n}\nfunction isLengthOnly(value) {\n return lengthUnitRegex.test(value);\n}\nfunction isNever() {\n return false;\n}\nfunction isUrl(value) {\n return value.startsWith('url(');\n}\nfunction isIntegerOnly(value) {\n return Number.isInteger(Number(value));\n}\nfunction isShadow(value) {\n return shadowRegex.test(value);\n}\n\nexport { isAny, isArbitraryLength, isArbitraryNumber, isArbitraryPosition, isArbitraryShadow, isArbitrarySize, isArbitraryUrl, isArbitraryValue, isArbitraryWeight, isInteger, isLength, isNumber, isPercent, isTshirtSize };\n//# sourceMappingURL=validators.mjs.map\n","import { fromTheme } from './from-theme.mjs';\nimport { isAny, isLength, isTshirtSize, isArbitraryValue, isPercent, isArbitraryLength, isInteger, isArbitraryNumber, isNumber, isArbitraryPosition, isArbitrarySize, isArbitraryUrl, isArbitraryShadow } from './validators.mjs';\n\nfunction getDefaultConfig() {\n var colors = fromTheme('colors');\n var spacing = fromTheme('spacing');\n var blur = fromTheme('blur');\n var brightness = fromTheme('brightness');\n var borderColor = fromTheme('borderColor');\n var borderRadius = fromTheme('borderRadius');\n var borderSpacing = fromTheme('borderSpacing');\n var borderWidth = fromTheme('borderWidth');\n var contrast = fromTheme('contrast');\n var grayscale = fromTheme('grayscale');\n var hueRotate = fromTheme('hueRotate');\n var invert = fromTheme('invert');\n var gap = fromTheme('gap');\n var gradientColorStops = fromTheme('gradientColorStops');\n var gradientColorStopPositions = fromTheme('gradientColorStopPositions');\n var inset = fromTheme('inset');\n var margin = fromTheme('margin');\n var opacity = fromTheme('opacity');\n var padding = fromTheme('padding');\n var saturate = fromTheme('saturate');\n var scale = fromTheme('scale');\n var sepia = fromTheme('sepia');\n var skew = fromTheme('skew');\n var space = fromTheme('space');\n var translate = fromTheme('translate');\n var getOverscroll = function getOverscroll() {\n return ['auto', 'contain', 'none'];\n };\n var getOverflow = function getOverflow() {\n return ['auto', 'hidden', 'clip', 'visible', 'scroll'];\n };\n var getSpacingWithAutoAndArbitrary = function getSpacingWithAutoAndArbitrary() {\n return ['auto', isArbitraryValue, spacing];\n };\n var getSpacingWithArbitrary = function getSpacingWithArbitrary() {\n return [isArbitraryValue, spacing];\n };\n var getLengthWithEmpty = function getLengthWithEmpty() {\n return ['', isLength];\n };\n var getNumberWithAutoAndArbitrary = function getNumberWithAutoAndArbitrary() {\n return ['auto', isNumber, isArbitraryValue];\n };\n var getPositions = function getPositions() {\n return ['bottom', 'center', 'left', 'left-bottom', 'left-top', 'right', 'right-bottom', 'right-top', 'top'];\n };\n var getLineStyles = function getLineStyles() {\n return ['solid', 'dashed', 'dotted', 'double', 'none'];\n };\n var getBlendModes = function getBlendModes() {\n return ['normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity', 'plus-lighter'];\n };\n var getAlign = function getAlign() {\n return ['start', 'end', 'center', 'between', 'around', 'evenly', 'stretch'];\n };\n var getZeroAndEmpty = function getZeroAndEmpty() {\n return ['', '0', isArbitraryValue];\n };\n var getBreaks = function getBreaks() {\n return ['auto', 'avoid', 'all', 'avoid-page', 'page', 'left', 'right', 'column'];\n };\n var getNumber = function getNumber() {\n return [isNumber, isArbitraryNumber];\n };\n var getNumberAndArbitrary = function getNumberAndArbitrary() {\n return [isNumber, isArbitraryValue];\n };\n return {\n cacheSize: 500,\n theme: {\n colors: [isAny],\n spacing: [isLength],\n blur: ['none', '', isTshirtSize, isArbitraryValue],\n brightness: getNumber(),\n borderColor: [colors],\n borderRadius: ['none', '', 'full', isTshirtSize, isArbitraryValue],\n borderSpacing: getSpacingWithArbitrary(),\n borderWidth: getLengthWithEmpty(),\n contrast: getNumber(),\n grayscale: getZeroAndEmpty(),\n hueRotate: getNumberAndArbitrary(),\n invert: getZeroAndEmpty(),\n gap: getSpacingWithArbitrary(),\n gradientColorStops: [colors],\n gradientColorStopPositions: [isPercent, isArbitraryLength],\n inset: getSpacingWithAutoAndArbitrary(),\n margin: getSpacingWithAutoAndArbitrary(),\n opacity: getNumber(),\n padding: getSpacingWithArbitrary(),\n saturate: getNumber(),\n scale: getNumber(),\n sepia: getZeroAndEmpty(),\n skew: getNumberAndArbitrary(),\n space: getSpacingWithArbitrary(),\n translate: getSpacingWithArbitrary()\n },\n classGroups: {\n // Layout\n /**\n * Aspect Ratio\n * @see https://tailwindcss.com/docs/aspect-ratio\n */\n aspect: [{\n aspect: ['auto', 'square', 'video', isArbitraryValue]\n }],\n /**\n * Container\n * @see https://tailwindcss.com/docs/container\n */\n container: ['container'],\n /**\n * Columns\n * @see https://tailwindcss.com/docs/columns\n */\n columns: [{\n columns: [isTshirtSize]\n }],\n /**\n * Break After\n * @see https://tailwindcss.com/docs/break-after\n */\n 'break-after': [{\n 'break-after': getBreaks()\n }],\n /**\n * Break Before\n * @see https://tailwindcss.com/docs/break-before\n */\n 'break-before': [{\n 'break-before': getBreaks()\n }],\n /**\n * Break Inside\n * @see https://tailwindcss.com/docs/break-inside\n */\n 'break-inside': [{\n 'break-inside': ['auto', 'avoid', 'avoid-page', 'avoid-column']\n }],\n /**\n * Box Decoration Break\n * @see https://tailwindcss.com/docs/box-decoration-break\n */\n 'box-decoration': [{\n 'box-decoration': ['slice', 'clone']\n }],\n /**\n * Box Sizing\n * @see https://tailwindcss.com/docs/box-sizing\n */\n box: [{\n box: ['border', 'content']\n }],\n /**\n * Display\n * @see https://tailwindcss.com/docs/display\n */\n display: ['block', 'inline-block', 'inline', 'flex', 'inline-flex', 'table', 'inline-table', 'table-caption', 'table-cell', 'table-column', 'table-column-group', 'table-footer-group', 'table-header-group', 'table-row-group', 'table-row', 'flow-root', 'grid', 'inline-grid', 'contents', 'list-item', 'hidden'],\n /**\n * Floats\n * @see https://tailwindcss.com/docs/float\n */\n \"float\": [{\n \"float\": ['right', 'left', 'none']\n }],\n /**\n * Clear\n * @see https://tailwindcss.com/docs/clear\n */\n clear: [{\n clear: ['left', 'right', 'both', 'none']\n }],\n /**\n * Isolation\n * @see https://tailwindcss.com/docs/isolation\n */\n isolation: ['isolate', 'isolation-auto'],\n /**\n * Object Fit\n * @see https://tailwindcss.com/docs/object-fit\n */\n 'object-fit': [{\n object: ['contain', 'cover', 'fill', 'none', 'scale-down']\n }],\n /**\n * Object Position\n * @see https://tailwindcss.com/docs/object-position\n */\n 'object-position': [{\n object: [].concat(getPositions(), [isArbitraryValue])\n }],\n /**\n * Overflow\n * @see https://tailwindcss.com/docs/overflow\n */\n overflow: [{\n overflow: getOverflow()\n }],\n /**\n * Overflow X\n * @see https://tailwindcss.com/docs/overflow\n */\n 'overflow-x': [{\n 'overflow-x': getOverflow()\n }],\n /**\n * Overflow Y\n * @see https://tailwindcss.com/docs/overflow\n */\n 'overflow-y': [{\n 'overflow-y': getOverflow()\n }],\n /**\n * Overscroll Behavior\n * @see https://tailwindcss.com/docs/overscroll-behavior\n */\n overscroll: [{\n overscroll: getOverscroll()\n }],\n /**\n * Overscroll Behavior X\n * @see https://tailwindcss.com/docs/overscroll-behavior\n */\n 'overscroll-x': [{\n 'overscroll-x': getOverscroll()\n }],\n /**\n * Overscroll Behavior Y\n * @see https://tailwindcss.com/docs/overscroll-behavior\n */\n 'overscroll-y': [{\n 'overscroll-y': getOverscroll()\n }],\n /**\n * Position\n * @see https://tailwindcss.com/docs/position\n */\n position: ['static', 'fixed', 'absolute', 'relative', 'sticky'],\n /**\n * Top / Right / Bottom / Left\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n inset: [{\n inset: [inset]\n }],\n /**\n * Right / Left\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n 'inset-x': [{\n 'inset-x': [inset]\n }],\n /**\n * Top / Bottom\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n 'inset-y': [{\n 'inset-y': [inset]\n }],\n /**\n * Start\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n start: [{\n start: [inset]\n }],\n /**\n * End\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n end: [{\n end: [inset]\n }],\n /**\n * Top\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n top: [{\n top: [inset]\n }],\n /**\n * Right\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n right: [{\n right: [inset]\n }],\n /**\n * Bottom\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n bottom: [{\n bottom: [inset]\n }],\n /**\n * Left\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n left: [{\n left: [inset]\n }],\n /**\n * Visibility\n * @see https://tailwindcss.com/docs/visibility\n */\n visibility: ['visible', 'invisible', 'collapse'],\n /**\n * Z-Index\n * @see https://tailwindcss.com/docs/z-index\n */\n z: [{\n z: ['auto', isInteger]\n }],\n // Flexbox and Grid\n /**\n * Flex Basis\n * @see https://tailwindcss.com/docs/flex-basis\n */\n basis: [{\n basis: getSpacingWithAutoAndArbitrary()\n }],\n /**\n * Flex Direction\n * @see https://tailwindcss.com/docs/flex-direction\n */\n 'flex-direction': [{\n flex: ['row', 'row-reverse', 'col', 'col-reverse']\n }],\n /**\n * Flex Wrap\n * @see https://tailwindcss.com/docs/flex-wrap\n */\n 'flex-wrap': [{\n flex: ['wrap', 'wrap-reverse', 'nowrap']\n }],\n /**\n * Flex\n * @see https://tailwindcss.com/docs/flex\n */\n flex: [{\n flex: ['1', 'auto', 'initial', 'none', isArbitraryValue]\n }],\n /**\n * Flex Grow\n * @see https://tailwindcss.com/docs/flex-grow\n */\n grow: [{\n grow: getZeroAndEmpty()\n }],\n /**\n * Flex Shrink\n * @see https://tailwindcss.com/docs/flex-shrink\n */\n shrink: [{\n shrink: getZeroAndEmpty()\n }],\n /**\n * Order\n * @see https://tailwindcss.com/docs/order\n */\n order: [{\n order: ['first', 'last', 'none', isInteger]\n }],\n /**\n * Grid Template Columns\n * @see https://tailwindcss.com/docs/grid-template-columns\n */\n 'grid-cols': [{\n 'grid-cols': [isAny]\n }],\n /**\n * Grid Column Start / End\n * @see https://tailwindcss.com/docs/grid-column\n */\n 'col-start-end': [{\n col: ['auto', {\n span: ['full', isInteger]\n }, isArbitraryValue]\n }],\n /**\n * Grid Column Start\n * @see https://tailwindcss.com/docs/grid-column\n */\n 'col-start': [{\n 'col-start': getNumberWithAutoAndArbitrary()\n }],\n /**\n * Grid Column End\n * @see https://tailwindcss.com/docs/grid-column\n */\n 'col-end': [{\n 'col-end': getNumberWithAutoAndArbitrary()\n }],\n /**\n * Grid Template Rows\n * @see https://tailwindcss.com/docs/grid-template-rows\n */\n 'grid-rows': [{\n 'grid-rows': [isAny]\n }],\n /**\n * Grid Row Start / End\n * @see https://tailwindcss.com/docs/grid-row\n */\n 'row-start-end': [{\n row: ['auto', {\n span: [isInteger]\n }, isArbitraryValue]\n }],\n /**\n * Grid Row Start\n * @see https://tailwindcss.com/docs/grid-row\n */\n 'row-start': [{\n 'row-start': getNumberWithAutoAndArbitrary()\n }],\n /**\n * Grid Row End\n * @see https://tailwindcss.com/docs/grid-row\n */\n 'row-end': [{\n 'row-end': getNumberWithAutoAndArbitrary()\n }],\n /**\n * Grid Auto Flow\n * @see https://tailwindcss.com/docs/grid-auto-flow\n */\n 'grid-flow': [{\n 'grid-flow': ['row', 'col', 'dense', 'row-dense', 'col-dense']\n }],\n /**\n * Grid Auto Columns\n * @see https://tailwindcss.com/docs/grid-auto-columns\n */\n 'auto-cols': [{\n 'auto-cols': ['auto', 'min', 'max', 'fr', isArbitraryValue]\n }],\n /**\n * Grid Auto Rows\n * @see https://tailwindcss.com/docs/grid-auto-rows\n */\n 'auto-rows': [{\n 'auto-rows': ['auto', 'min', 'max', 'fr', isArbitraryValue]\n }],\n /**\n * Gap\n * @see https://tailwindcss.com/docs/gap\n */\n gap: [{\n gap: [gap]\n }],\n /**\n * Gap X\n * @see https://tailwindcss.com/docs/gap\n */\n 'gap-x': [{\n 'gap-x': [gap]\n }],\n /**\n * Gap Y\n * @see https://tailwindcss.com/docs/gap\n */\n 'gap-y': [{\n 'gap-y': [gap]\n }],\n /**\n * Justify Content\n * @see https://tailwindcss.com/docs/justify-content\n */\n 'justify-content': [{\n justify: ['normal'].concat(getAlign())\n }],\n /**\n * Justify Items\n * @see https://tailwindcss.com/docs/justify-items\n */\n 'justify-items': [{\n 'justify-items': ['start', 'end', 'center', 'stretch']\n }],\n /**\n * Justify Self\n * @see https://tailwindcss.com/docs/justify-self\n */\n 'justify-self': [{\n 'justify-self': ['auto', 'start', 'end', 'center', 'stretch']\n }],\n /**\n * Align Content\n * @see https://tailwindcss.com/docs/align-content\n */\n 'align-content': [{\n content: ['normal'].concat(getAlign(), ['baseline'])\n }],\n /**\n * Align Items\n * @see https://tailwindcss.com/docs/align-items\n */\n 'align-items': [{\n items: ['start', 'end', 'center', 'baseline', 'stretch']\n }],\n /**\n * Align Self\n * @see https://tailwindcss.com/docs/align-self\n */\n 'align-self': [{\n self: ['auto', 'start', 'end', 'center', 'stretch', 'baseline']\n }],\n /**\n * Place Content\n * @see https://tailwindcss.com/docs/place-content\n */\n 'place-content': [{\n 'place-content': [].concat(getAlign(), ['baseline'])\n }],\n /**\n * Place Items\n * @see https://tailwindcss.com/docs/place-items\n */\n 'place-items': [{\n 'place-items': ['start', 'end', 'center', 'baseline', 'stretch']\n }],\n /**\n * Place Self\n * @see https://tailwindcss.com/docs/place-self\n */\n 'place-self': [{\n 'place-self': ['auto', 'start', 'end', 'center', 'stretch']\n }],\n // Spacing\n /**\n * Padding\n * @see https://tailwindcss.com/docs/padding\n */\n p: [{\n p: [padding]\n }],\n /**\n * Padding X\n * @see https://tailwindcss.com/docs/padding\n */\n px: [{\n px: [padding]\n }],\n /**\n * Padding Y\n * @see https://tailwindcss.com/docs/padding\n */\n py: [{\n py: [padding]\n }],\n /**\n * Padding Start\n * @see https://tailwindcss.com/docs/padding\n */\n ps: [{\n ps: [padding]\n }],\n /**\n * Padding End\n * @see https://tailwindcss.com/docs/padding\n */\n pe: [{\n pe: [padding]\n }],\n /**\n * Padding Top\n * @see https://tailwindcss.com/docs/padding\n */\n pt: [{\n pt: [padding]\n }],\n /**\n * Padding Right\n * @see https://tailwindcss.com/docs/padding\n */\n pr: [{\n pr: [padding]\n }],\n /**\n * Padding Bottom\n * @see https://tailwindcss.com/docs/padding\n */\n pb: [{\n pb: [padding]\n }],\n /**\n * Padding Left\n * @see https://tailwindcss.com/docs/padding\n */\n pl: [{\n pl: [padding]\n }],\n /**\n * Margin\n * @see https://tailwindcss.com/docs/margin\n */\n m: [{\n m: [margin]\n }],\n /**\n * Margin X\n * @see https://tailwindcss.com/docs/margin\n */\n mx: [{\n mx: [margin]\n }],\n /**\n * Margin Y\n * @see https://tailwindcss.com/docs/margin\n */\n my: [{\n my: [margin]\n }],\n /**\n * Margin Start\n * @see https://tailwindcss.com/docs/margin\n */\n ms: [{\n ms: [margin]\n }],\n /**\n * Margin End\n * @see https://tailwindcss.com/docs/margin\n */\n me: [{\n me: [margin]\n }],\n /**\n * Margin Top\n * @see https://tailwindcss.com/docs/margin\n */\n mt: [{\n mt: [margin]\n }],\n /**\n * Margin Right\n * @see https://tailwindcss.com/docs/margin\n */\n mr: [{\n mr: [margin]\n }],\n /**\n * Margin Bottom\n * @see https://tailwindcss.com/docs/margin\n */\n mb: [{\n mb: [margin]\n }],\n /**\n * Margin Left\n * @see https://tailwindcss.com/docs/margin\n */\n ml: [{\n ml: [margin]\n }],\n /**\n * Space Between X\n * @see https://tailwindcss.com/docs/space\n */\n 'space-x': [{\n 'space-x': [space]\n }],\n /**\n * Space Between X Reverse\n * @see https://tailwindcss.com/docs/space\n */\n 'space-x-reverse': ['space-x-reverse'],\n /**\n * Space Between Y\n * @see https://tailwindcss.com/docs/space\n */\n 'space-y': [{\n 'space-y': [space]\n }],\n /**\n * Space Between Y Reverse\n * @see https://tailwindcss.com/docs/space\n */\n 'space-y-reverse': ['space-y-reverse'],\n // Sizing\n /**\n * Width\n * @see https://tailwindcss.com/docs/width\n */\n w: [{\n w: ['auto', 'min', 'max', 'fit', isArbitraryValue, spacing]\n }],\n /**\n * Min-Width\n * @see https://tailwindcss.com/docs/min-width\n */\n 'min-w': [{\n 'min-w': ['min', 'max', 'fit', isArbitraryValue, isLength]\n }],\n /**\n * Max-Width\n * @see https://tailwindcss.com/docs/max-width\n */\n 'max-w': [{\n 'max-w': ['0', 'none', 'full', 'min', 'max', 'fit', 'prose', {\n screen: [isTshirtSize]\n }, isTshirtSize, isArbitraryValue]\n }],\n /**\n * Height\n * @see https://tailwindcss.com/docs/height\n */\n h: [{\n h: [isArbitraryValue, spacing, 'auto', 'min', 'max', 'fit']\n }],\n /**\n * Min-Height\n * @see https://tailwindcss.com/docs/min-height\n */\n 'min-h': [{\n 'min-h': ['min', 'max', 'fit', isArbitraryValue, isLength]\n }],\n /**\n * Max-Height\n * @see https://tailwindcss.com/docs/max-height\n */\n 'max-h': [{\n 'max-h': [isArbitraryValue, spacing, 'min', 'max', 'fit']\n }],\n // Typography\n /**\n * Font Size\n * @see https://tailwindcss.com/docs/font-size\n */\n 'font-size': [{\n text: ['base', isTshirtSize, isArbitraryLength]\n }],\n /**\n * Font Smoothing\n * @see https://tailwindcss.com/docs/font-smoothing\n */\n 'font-smoothing': ['antialiased', 'subpixel-antialiased'],\n /**\n * Font Style\n * @see https://tailwindcss.com/docs/font-style\n */\n 'font-style': ['italic', 'not-italic'],\n /**\n * Font Weight\n * @see https://tailwindcss.com/docs/font-weight\n */\n 'font-weight': [{\n font: ['thin', 'extralight', 'light', 'normal', 'medium', 'semibold', 'bold', 'extrabold', 'black', isArbitraryNumber]\n }],\n /**\n * Font Family\n * @see https://tailwindcss.com/docs/font-family\n */\n 'font-family': [{\n font: [isAny]\n }],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-normal': ['normal-nums'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-ordinal': ['ordinal'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-slashed-zero': ['slashed-zero'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-figure': ['lining-nums', 'oldstyle-nums'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-spacing': ['proportional-nums', 'tabular-nums'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-fraction': ['diagonal-fractions', 'stacked-fractons'],\n /**\n * Letter Spacing\n * @see https://tailwindcss.com/docs/letter-spacing\n */\n tracking: [{\n tracking: ['tighter', 'tight', 'normal', 'wide', 'wider', 'widest', isArbitraryValue]\n }],\n /**\n * Line Clamp\n * @see https://tailwindcss.com/docs/line-clamp\n */\n 'line-clamp': [{\n 'line-clamp': ['none', isNumber, isArbitraryNumber]\n }],\n /**\n * Line Height\n * @see https://tailwindcss.com/docs/line-height\n */\n leading: [{\n leading: ['none', 'tight', 'snug', 'normal', 'relaxed', 'loose', isArbitraryValue, isLength]\n }],\n /**\n * List Style Image\n * @see https://tailwindcss.com/docs/list-style-image\n */\n 'list-image': [{\n 'list-image': ['none', isArbitraryValue]\n }],\n /**\n * List Style Type\n * @see https://tailwindcss.com/docs/list-style-type\n */\n 'list-style-type': [{\n list: ['none', 'disc', 'decimal', isArbitraryValue]\n }],\n /**\n * List Style Position\n * @see https://tailwindcss.com/docs/list-style-position\n */\n 'list-style-position': [{\n list: ['inside', 'outside']\n }],\n /**\n * Placeholder Color\n * @deprecated since Tailwind CSS v3.0.0\n * @see https://tailwindcss.com/docs/placeholder-color\n */\n 'placeholder-color': [{\n placeholder: [colors]\n }],\n /**\n * Placeholder Opacity\n * @see https://tailwindcss.com/docs/placeholder-opacity\n */\n 'placeholder-opacity': [{\n 'placeholder-opacity': [opacity]\n }],\n /**\n * Text Alignment\n * @see https://tailwindcss.com/docs/text-align\n */\n 'text-alignment': [{\n text: ['left', 'center', 'right', 'justify', 'start', 'end']\n }],\n /**\n * Text Color\n * @see https://tailwindcss.com/docs/text-color\n */\n 'text-color': [{\n text: [colors]\n }],\n /**\n * Text Opacity\n * @see https://tailwindcss.com/docs/text-opacity\n */\n 'text-opacity': [{\n 'text-opacity': [opacity]\n }],\n /**\n * Text Decoration\n * @see https://tailwindcss.com/docs/text-decoration\n */\n 'text-decoration': ['underline', 'overline', 'line-through', 'no-underline'],\n /**\n * Text Decoration Style\n * @see https://tailwindcss.com/docs/text-decoration-style\n */\n 'text-decoration-style': [{\n decoration: [].concat(getLineStyles(), ['wavy'])\n }],\n /**\n * Text Decoration Thickness\n * @see https://tailwindcss.com/docs/text-decoration-thickness\n */\n 'text-decoration-thickness': [{\n decoration: ['auto', 'from-font', isLength]\n }],\n /**\n * Text Underline Offset\n * @see https://tailwindcss.com/docs/text-underline-offset\n */\n 'underline-offset': [{\n 'underline-offset': ['auto', isArbitraryValue, isLength]\n }],\n /**\n * Text Decoration Color\n * @see https://tailwindcss.com/docs/text-decoration-color\n */\n 'text-decoration-color': [{\n decoration: [colors]\n }],\n /**\n * Text Transform\n * @see https://tailwindcss.com/docs/text-transform\n */\n 'text-transform': ['uppercase', 'lowercase', 'capitalize', 'normal-case'],\n /**\n * Text Overflow\n * @see https://tailwindcss.com/docs/text-overflow\n */\n 'text-overflow': ['truncate', 'text-ellipsis', 'text-clip'],\n /**\n * Text Indent\n * @see https://tailwindcss.com/docs/text-indent\n */\n indent: [{\n indent: getSpacingWithArbitrary()\n }],\n /**\n * Vertical Alignment\n * @see https://tailwindcss.com/docs/vertical-align\n */\n 'vertical-align': [{\n align: ['baseline', 'top', 'middle', 'bottom', 'text-top', 'text-bottom', 'sub', 'super', isArbitraryValue]\n }],\n /**\n * Whitespace\n * @see https://tailwindcss.com/docs/whitespace\n */\n whitespace: [{\n whitespace: ['normal', 'nowrap', 'pre', 'pre-line', 'pre-wrap', 'break-spaces']\n }],\n /**\n * Word Break\n * @see https://tailwindcss.com/docs/word-break\n */\n \"break\": [{\n \"break\": ['normal', 'words', 'all', 'keep']\n }],\n /**\n * Hyphens\n * @see https://tailwindcss.com/docs/hyphens\n */\n hyphens: [{\n hyphens: ['none', 'manual', 'auto']\n }],\n /**\n * Content\n * @see https://tailwindcss.com/docs/content\n */\n content: [{\n content: ['none', isArbitraryValue]\n }],\n // Backgrounds\n /**\n * Background Attachment\n * @see https://tailwindcss.com/docs/background-attachment\n */\n 'bg-attachment': [{\n bg: ['fixed', 'local', 'scroll']\n }],\n /**\n * Background Clip\n * @see https://tailwindcss.com/docs/background-clip\n */\n 'bg-clip': [{\n 'bg-clip': ['border', 'padding', 'content', 'text']\n }],\n /**\n * Background Opacity\n * @deprecated since Tailwind CSS v3.0.0\n * @see https://tailwindcss.com/docs/background-opacity\n */\n 'bg-opacity': [{\n 'bg-opacity': [opacity]\n }],\n /**\n * Background Origin\n * @see https://tailwindcss.com/docs/background-origin\n */\n 'bg-origin': [{\n 'bg-origin': ['border', 'padding', 'content']\n }],\n /**\n * Background Position\n * @see https://tailwindcss.com/docs/background-position\n */\n 'bg-position': [{\n bg: [].concat(getPositions(), [isArbitraryPosition])\n }],\n /**\n * Background Repeat\n * @see https://tailwindcss.com/docs/background-repeat\n */\n 'bg-repeat': [{\n bg: ['no-repeat', {\n repeat: ['', 'x', 'y', 'round', 'space']\n }]\n }],\n /**\n * Background Size\n * @see https://tailwindcss.com/docs/background-size\n */\n 'bg-size': [{\n bg: ['auto', 'cover', 'contain', isArbitrarySize]\n }],\n /**\n * Background Image\n * @see https://tailwindcss.com/docs/background-image\n */\n 'bg-image': [{\n bg: ['none', {\n 'gradient-to': ['t', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl']\n }, isArbitraryUrl]\n }],\n /**\n * Background Color\n * @see https://tailwindcss.com/docs/background-color\n */\n 'bg-color': [{\n bg: [colors]\n }],\n /**\n * Gradient Color Stops From Position\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-from-pos': [{\n from: [gradientColorStopPositions]\n }],\n /**\n * Gradient Color Stops Via Position\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-via-pos': [{\n via: [gradientColorStopPositions]\n }],\n /**\n * Gradient Color Stops To Position\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-to-pos': [{\n to: [gradientColorStopPositions]\n }],\n /**\n * Gradient Color Stops From\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-from': [{\n from: [gradientColorStops]\n }],\n /**\n * Gradient Color Stops Via\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-via': [{\n via: [gradientColorStops]\n }],\n /**\n * Gradient Color Stops To\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-to': [{\n to: [gradientColorStops]\n }],\n // Borders\n /**\n * Border Radius\n * @see https://tailwindcss.com/docs/border-radius\n */\n rounded: [{\n rounded: [borderRadius]\n }],\n /**\n * Border Radius Start\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-s': [{\n 'rounded-s': [borderRadius]\n }],\n /**\n * Border Radius End\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-e': [{\n 'rounded-e': [borderRadius]\n }],\n /**\n * Border Radius Top\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-t': [{\n 'rounded-t': [borderRadius]\n }],\n /**\n * Border Radius Right\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-r': [{\n 'rounded-r': [borderRadius]\n }],\n /**\n * Border Radius Bottom\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-b': [{\n 'rounded-b': [borderRadius]\n }],\n /**\n * Border Radius Left\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-l': [{\n 'rounded-l': [borderRadius]\n }],\n /**\n * Border Radius Start Start\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-ss': [{\n 'rounded-ss': [borderRadius]\n }],\n /**\n * Border Radius Start End\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-se': [{\n 'rounded-se': [borderRadius]\n }],\n /**\n * Border Radius End End\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-ee': [{\n 'rounded-ee': [borderRadius]\n }],\n /**\n * Border Radius End Start\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-es': [{\n 'rounded-es': [borderRadius]\n }],\n /**\n * Border Radius Top Left\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-tl': [{\n 'rounded-tl': [borderRadius]\n }],\n /**\n * Border Radius Top Right\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-tr': [{\n 'rounded-tr': [borderRadius]\n }],\n /**\n * Border Radius Bottom Right\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-br': [{\n 'rounded-br': [borderRadius]\n }],\n /**\n * Border Radius Bottom Left\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-bl': [{\n 'rounded-bl': [borderRadius]\n }],\n /**\n * Border Width\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w': [{\n border: [borderWidth]\n }],\n /**\n * Border Width X\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-x': [{\n 'border-x': [borderWidth]\n }],\n /**\n * Border Width Y\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-y': [{\n 'border-y': [borderWidth]\n }],\n /**\n * Border Width Start\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-s': [{\n 'border-s': [borderWidth]\n }],\n /**\n * Border Width End\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-e': [{\n 'border-e': [borderWidth]\n }],\n /**\n * Border Width Top\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-t': [{\n 'border-t': [borderWidth]\n }],\n /**\n * Border Width Right\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-r': [{\n 'border-r': [borderWidth]\n }],\n /**\n * Border Width Bottom\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-b': [{\n 'border-b': [borderWidth]\n }],\n /**\n * Border Width Left\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-l': [{\n 'border-l': [borderWidth]\n }],\n /**\n * Border Opacity\n * @see https://tailwindcss.com/docs/border-opacity\n */\n 'border-opacity': [{\n 'border-opacity': [opacity]\n }],\n /**\n * Border Style\n * @see https://tailwindcss.com/docs/border-style\n */\n 'border-style': [{\n border: [].concat(getLineStyles(), ['hidden'])\n }],\n /**\n * Divide Width X\n * @see https://tailwindcss.com/docs/divide-width\n */\n 'divide-x': [{\n 'divide-x': [borderWidth]\n }],\n /**\n * Divide Width X Reverse\n * @see https://tailwindcss.com/docs/divide-width\n */\n 'divide-x-reverse': ['divide-x-reverse'],\n /**\n * Divide Width Y\n * @see https://tailwindcss.com/docs/divide-width\n */\n 'divide-y': [{\n 'divide-y': [borderWidth]\n }],\n /**\n * Divide Width Y Reverse\n * @see https://tailwindcss.com/docs/divide-width\n */\n 'divide-y-reverse': ['divide-y-reverse'],\n /**\n * Divide Opacity\n * @see https://tailwindcss.com/docs/divide-opacity\n */\n 'divide-opacity': [{\n 'divide-opacity': [opacity]\n }],\n /**\n * Divide Style\n * @see https://tailwindcss.com/docs/divide-style\n */\n 'divide-style': [{\n divide: getLineStyles()\n }],\n /**\n * Border Color\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color': [{\n border: [borderColor]\n }],\n /**\n * Border Color X\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-x': [{\n 'border-x': [borderColor]\n }],\n /**\n * Border Color Y\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-y': [{\n 'border-y': [borderColor]\n }],\n /**\n * Border Color Top\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-t': [{\n 'border-t': [borderColor]\n }],\n /**\n * Border Color Right\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-r': [{\n 'border-r': [borderColor]\n }],\n /**\n * Border Color Bottom\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-b': [{\n 'border-b': [borderColor]\n }],\n /**\n * Border Color Left\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-l': [{\n 'border-l': [borderColor]\n }],\n /**\n * Divide Color\n * @see https://tailwindcss.com/docs/divide-color\n */\n 'divide-color': [{\n divide: [borderColor]\n }],\n /**\n * Outline Style\n * @see https://tailwindcss.com/docs/outline-style\n */\n 'outline-style': [{\n outline: [''].concat(getLineStyles())\n }],\n /**\n * Outline Offset\n * @see https://tailwindcss.com/docs/outline-offset\n */\n 'outline-offset': [{\n 'outline-offset': [isArbitraryValue, isLength]\n }],\n /**\n * Outline Width\n * @see https://tailwindcss.com/docs/outline-width\n */\n 'outline-w': [{\n outline: [isLength]\n }],\n /**\n * Outline Color\n * @see https://tailwindcss.com/docs/outline-color\n */\n 'outline-color': [{\n outline: [colors]\n }],\n /**\n * Ring Width\n * @see https://tailwindcss.com/docs/ring-width\n */\n 'ring-w': [{\n ring: getLengthWithEmpty()\n }],\n /**\n * Ring Width Inset\n * @see https://tailwindcss.com/docs/ring-width\n */\n 'ring-w-inset': ['ring-inset'],\n /**\n * Ring Color\n * @see https://tailwindcss.com/docs/ring-color\n */\n 'ring-color': [{\n ring: [colors]\n }],\n /**\n * Ring Opacity\n * @see https://tailwindcss.com/docs/ring-opacity\n */\n 'ring-opacity': [{\n 'ring-opacity': [opacity]\n }],\n /**\n * Ring Offset Width\n * @see https://tailwindcss.com/docs/ring-offset-width\n */\n 'ring-offset-w': [{\n 'ring-offset': [isLength]\n }],\n /**\n * Ring Offset Color\n * @see https://tailwindcss.com/docs/ring-offset-color\n */\n 'ring-offset-color': [{\n 'ring-offset': [colors]\n }],\n // Effects\n /**\n * Box Shadow\n * @see https://tailwindcss.com/docs/box-shadow\n */\n shadow: [{\n shadow: ['', 'inner', 'none', isTshirtSize, isArbitraryShadow]\n }],\n /**\n * Box Shadow Color\n * @see https://tailwindcss.com/docs/box-shadow-color\n */\n 'shadow-color': [{\n shadow: [isAny]\n }],\n /**\n * Opacity\n * @see https://tailwindcss.com/docs/opacity\n */\n opacity: [{\n opacity: [opacity]\n }],\n /**\n * Mix Blend Mode\n * @see https://tailwindcss.com/docs/mix-blend-mode\n */\n 'mix-blend': [{\n 'mix-blend': getBlendModes()\n }],\n /**\n * Background Blend Mode\n * @see https://tailwindcss.com/docs/background-blend-mode\n */\n 'bg-blend': [{\n 'bg-blend': getBlendModes()\n }],\n // Filters\n /**\n * Filter\n * @deprecated since Tailwind CSS v3.0.0\n * @see https://tailwindcss.com/docs/filter\n */\n filter: [{\n filter: ['', 'none']\n }],\n /**\n * Blur\n * @see https://tailwindcss.com/docs/blur\n */\n blur: [{\n blur: [blur]\n }],\n /**\n * Brightness\n * @see https://tailwindcss.com/docs/brightness\n */\n brightness: [{\n brightness: [brightness]\n }],\n /**\n * Contrast\n * @see https://tailwindcss.com/docs/contrast\n */\n contrast: [{\n contrast: [contrast]\n }],\n /**\n * Drop Shadow\n * @see https://tailwindcss.com/docs/drop-shadow\n */\n 'drop-shadow': [{\n 'drop-shadow': ['', 'none', isTshirtSize, isArbitraryValue]\n }],\n /**\n * Grayscale\n * @see https://tailwindcss.com/docs/grayscale\n */\n grayscale: [{\n grayscale: [grayscale]\n }],\n /**\n * Hue Rotate\n * @see https://tailwindcss.com/docs/hue-rotate\n */\n 'hue-rotate': [{\n 'hue-rotate': [hueRotate]\n }],\n /**\n * Invert\n * @see https://tailwindcss.com/docs/invert\n */\n invert: [{\n invert: [invert]\n }],\n /**\n * Saturate\n * @see https://tailwindcss.com/docs/saturate\n */\n saturate: [{\n saturate: [saturate]\n }],\n /**\n * Sepia\n * @see https://tailwindcss.com/docs/sepia\n */\n sepia: [{\n sepia: [sepia]\n }],\n /**\n * Backdrop Filter\n * @deprecated since Tailwind CSS v3.0.0\n * @see https://tailwindcss.com/docs/backdrop-filter\n */\n 'backdrop-filter': [{\n 'backdrop-filter': ['', 'none']\n }],\n /**\n * Backdrop Blur\n * @see https://tailwindcss.com/docs/backdrop-blur\n */\n 'backdrop-blur': [{\n 'backdrop-blur': [blur]\n }],\n /**\n * Backdrop Brightness\n * @see https://tailwindcss.com/docs/backdrop-brightness\n */\n 'backdrop-brightness': [{\n 'backdrop-brightness': [brightness]\n }],\n /**\n * Backdrop Contrast\n * @see https://tailwindcss.com/docs/backdrop-contrast\n */\n 'backdrop-contrast': [{\n 'backdrop-contrast': [contrast]\n }],\n /**\n * Backdrop Grayscale\n * @see https://tailwindcss.com/docs/backdrop-grayscale\n */\n 'backdrop-grayscale': [{\n 'backdrop-grayscale': [grayscale]\n }],\n /**\n * Backdrop Hue Rotate\n * @see https://tailwindcss.com/docs/backdrop-hue-rotate\n */\n 'backdrop-hue-rotate': [{\n 'backdrop-hue-rotate': [hueRotate]\n }],\n /**\n * Backdrop Invert\n * @see https://tailwindcss.com/docs/backdrop-invert\n */\n 'backdrop-invert': [{\n 'backdrop-invert': [invert]\n }],\n /**\n * Backdrop Opacity\n * @see https://tailwindcss.com/docs/backdrop-opacity\n */\n 'backdrop-opacity': [{\n 'backdrop-opacity': [opacity]\n }],\n /**\n * Backdrop Saturate\n * @see https://tailwindcss.com/docs/backdrop-saturate\n */\n 'backdrop-saturate': [{\n 'backdrop-saturate': [saturate]\n }],\n /**\n * Backdrop Sepia\n * @see https://tailwindcss.com/docs/backdrop-sepia\n */\n 'backdrop-sepia': [{\n 'backdrop-sepia': [sepia]\n }],\n // Tables\n /**\n * Border Collapse\n * @see https://tailwindcss.com/docs/border-collapse\n */\n 'border-collapse': [{\n border: ['collapse', 'separate']\n }],\n /**\n * Border Spacing\n * @see https://tailwindcss.com/docs/border-spacing\n */\n 'border-spacing': [{\n 'border-spacing': [borderSpacing]\n }],\n /**\n * Border Spacing X\n * @see https://tailwindcss.com/docs/border-spacing\n */\n 'border-spacing-x': [{\n 'border-spacing-x': [borderSpacing]\n }],\n /**\n * Border Spacing Y\n * @see https://tailwindcss.com/docs/border-spacing\n */\n 'border-spacing-y': [{\n 'border-spacing-y': [borderSpacing]\n }],\n /**\n * Table Layout\n * @see https://tailwindcss.com/docs/table-layout\n */\n 'table-layout': [{\n table: ['auto', 'fixed']\n }],\n /**\n * Caption Side\n * @see https://tailwindcss.com/docs/caption-side\n */\n caption: [{\n caption: ['top', 'bottom']\n }],\n // Transitions and Animation\n /**\n * Tranisition Property\n * @see https://tailwindcss.com/docs/transition-property\n */\n transition: [{\n transition: ['none', 'all', '', 'colors', 'opacity', 'shadow', 'transform', isArbitraryValue]\n }],\n /**\n * Transition Duration\n * @see https://tailwindcss.com/docs/transition-duration\n */\n duration: [{\n duration: getNumberAndArbitrary()\n }],\n /**\n * Transition Timing Function\n * @see https://tailwindcss.com/docs/transition-timing-function\n */\n ease: [{\n ease: ['linear', 'in', 'out', 'in-out', isArbitraryValue]\n }],\n /**\n * Transition Delay\n * @see https://tailwindcss.com/docs/transition-delay\n */\n delay: [{\n delay: getNumberAndArbitrary()\n }],\n /**\n * Animation\n * @see https://tailwindcss.com/docs/animation\n */\n animate: [{\n animate: ['none', 'spin', 'ping', 'pulse', 'bounce', isArbitraryValue]\n }],\n // Transforms\n /**\n * Transform\n * @see https://tailwindcss.com/docs/transform\n */\n transform: [{\n transform: ['', 'gpu', 'none']\n }],\n /**\n * Scale\n * @see https://tailwindcss.com/docs/scale\n */\n scale: [{\n scale: [scale]\n }],\n /**\n * Scale X\n * @see https://tailwindcss.com/docs/scale\n */\n 'scale-x': [{\n 'scale-x': [scale]\n }],\n /**\n * Scale Y\n * @see https://tailwindcss.com/docs/scale\n */\n 'scale-y': [{\n 'scale-y': [scale]\n }],\n /**\n * Rotate\n * @see https://tailwindcss.com/docs/rotate\n */\n rotate: [{\n rotate: [isInteger, isArbitraryValue]\n }],\n /**\n * Translate X\n * @see https://tailwindcss.com/docs/translate\n */\n 'translate-x': [{\n 'translate-x': [translate]\n }],\n /**\n * Translate Y\n * @see https://tailwindcss.com/docs/translate\n */\n 'translate-y': [{\n 'translate-y': [translate]\n }],\n /**\n * Skew X\n * @see https://tailwindcss.com/docs/skew\n */\n 'skew-x': [{\n 'skew-x': [skew]\n }],\n /**\n * Skew Y\n * @see https://tailwindcss.com/docs/skew\n */\n 'skew-y': [{\n 'skew-y': [skew]\n }],\n /**\n * Transform Origin\n * @see https://tailwindcss.com/docs/transform-origin\n */\n 'transform-origin': [{\n origin: ['center', 'top', 'top-right', 'right', 'bottom-right', 'bottom', 'bottom-left', 'left', 'top-left', isArbitraryValue]\n }],\n // Interactivity\n /**\n * Accent Color\n * @see https://tailwindcss.com/docs/accent-color\n */\n accent: [{\n accent: ['auto', colors]\n }],\n /**\n * Appearance\n * @see https://tailwindcss.com/docs/appearance\n */\n appearance: ['appearance-none'],\n /**\n * Cursor\n * @see https://tailwindcss.com/docs/cursor\n */\n cursor: [{\n cursor: ['auto', 'default', 'pointer', 'wait', 'text', 'move', 'help', 'not-allowed', 'none', 'context-menu', 'progress', 'cell', 'crosshair', 'vertical-text', 'alias', 'copy', 'no-drop', 'grab', 'grabbing', 'all-scroll', 'col-resize', 'row-resize', 'n-resize', 'e-resize', 's-resize', 'w-resize', 'ne-resize', 'nw-resize', 'se-resize', 'sw-resize', 'ew-resize', 'ns-resize', 'nesw-resize', 'nwse-resize', 'zoom-in', 'zoom-out', isArbitraryValue]\n }],\n /**\n * Caret Color\n * @see https://tailwindcss.com/docs/just-in-time-mode#caret-color-utilities\n */\n 'caret-color': [{\n caret: [colors]\n }],\n /**\n * Pointer Events\n * @see https://tailwindcss.com/docs/pointer-events\n */\n 'pointer-events': [{\n 'pointer-events': ['none', 'auto']\n }],\n /**\n * Resize\n * @see https://tailwindcss.com/docs/resize\n */\n resize: [{\n resize: ['none', 'y', 'x', '']\n }],\n /**\n * Scroll Behavior\n * @see https://tailwindcss.com/docs/scroll-behavior\n */\n 'scroll-behavior': [{\n scroll: ['auto', 'smooth']\n }],\n /**\n * Scroll Margin\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-m': [{\n 'scroll-m': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Margin X\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mx': [{\n 'scroll-mx': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Margin Y\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-my': [{\n 'scroll-my': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Margin Start\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-ms': [{\n 'scroll-ms': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Margin End\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-me': [{\n 'scroll-me': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Margin Top\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mt': [{\n 'scroll-mt': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Margin Right\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mr': [{\n 'scroll-mr': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Margin Bottom\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mb': [{\n 'scroll-mb': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Margin Left\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-ml': [{\n 'scroll-ml': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Padding\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-p': [{\n 'scroll-p': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Padding X\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-px': [{\n 'scroll-px': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Padding Y\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-py': [{\n 'scroll-py': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Padding Start\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-ps': [{\n 'scroll-ps': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Padding End\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pe': [{\n 'scroll-pe': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Padding Top\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pt': [{\n 'scroll-pt': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Padding Right\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pr': [{\n 'scroll-pr': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Padding Bottom\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pb': [{\n 'scroll-pb': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Padding Left\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pl': [{\n 'scroll-pl': getSpacingWithArbitrary()\n }],\n /**\n * Scroll Snap Align\n * @see https://tailwindcss.com/docs/scroll-snap-align\n */\n 'snap-align': [{\n snap: ['start', 'end', 'center', 'align-none']\n }],\n /**\n * Scroll Snap Stop\n * @see https://tailwindcss.com/docs/scroll-snap-stop\n */\n 'snap-stop': [{\n snap: ['normal', 'always']\n }],\n /**\n * Scroll Snap Type\n * @see https://tailwindcss.com/docs/scroll-snap-type\n */\n 'snap-type': [{\n snap: ['none', 'x', 'y', 'both']\n }],\n /**\n * Scroll Snap Type Strictness\n * @see https://tailwindcss.com/docs/scroll-snap-type\n */\n 'snap-strictness': [{\n snap: ['mandatory', 'proximity']\n }],\n /**\n * Touch Action\n * @see https://tailwindcss.com/docs/touch-action\n */\n touch: [{\n touch: ['auto', 'none', 'pinch-zoom', 'manipulation', {\n pan: ['x', 'left', 'right', 'y', 'up', 'down']\n }]\n }],\n /**\n * User Select\n * @see https://tailwindcss.com/docs/user-select\n */\n select: [{\n select: ['none', 'text', 'all', 'auto']\n }],\n /**\n * Will Change\n * @see https://tailwindcss.com/docs/will-change\n */\n 'will-change': [{\n 'will-change': ['auto', 'scroll', 'contents', 'transform', isArbitraryValue]\n }],\n // SVG\n /**\n * Fill\n * @see https://tailwindcss.com/docs/fill\n */\n fill: [{\n fill: [colors, 'none']\n }],\n /**\n * Stroke Width\n * @see https://tailwindcss.com/docs/stroke-width\n */\n 'stroke-w': [{\n stroke: [isLength, isArbitraryNumber]\n }],\n /**\n * Stroke\n * @see https://tailwindcss.com/docs/stroke\n */\n stroke: [{\n stroke: [colors, 'none']\n }],\n // Accessibility\n /**\n * Screen Readers\n * @see https://tailwindcss.com/docs/screen-readers\n */\n sr: ['sr-only', 'not-sr-only']\n },\n conflictingClassGroups: {\n overflow: ['overflow-x', 'overflow-y'],\n overscroll: ['overscroll-x', 'overscroll-y'],\n inset: ['inset-x', 'inset-y', 'start', 'end', 'top', 'right', 'bottom', 'left'],\n 'inset-x': ['right', 'left'],\n 'inset-y': ['top', 'bottom'],\n flex: ['basis', 'grow', 'shrink'],\n gap: ['gap-x', 'gap-y'],\n p: ['px', 'py', 'ps', 'pe', 'pt', 'pr', 'pb', 'pl'],\n px: ['pr', 'pl'],\n py: ['pt', 'pb'],\n m: ['mx', 'my', 'ms', 'me', 'mt', 'mr', 'mb', 'ml'],\n mx: ['mr', 'ml'],\n my: ['mt', 'mb'],\n 'font-size': ['leading'],\n 'fvn-normal': ['fvn-ordinal', 'fvn-slashed-zero', 'fvn-figure', 'fvn-spacing', 'fvn-fraction'],\n 'fvn-ordinal': ['fvn-normal'],\n 'fvn-slashed-zero': ['fvn-normal'],\n 'fvn-figure': ['fvn-normal'],\n 'fvn-spacing': ['fvn-normal'],\n 'fvn-fraction': ['fvn-normal'],\n rounded: ['rounded-s', 'rounded-e', 'rounded-t', 'rounded-r', 'rounded-b', 'rounded-l', 'rounded-ss', 'rounded-se', 'rounded-ee', 'rounded-es', 'rounded-tl', 'rounded-tr', 'rounded-br', 'rounded-bl'],\n 'rounded-s': ['rounded-ss', 'rounded-es'],\n 'rounded-e': ['rounded-se', 'rounded-ee'],\n 'rounded-t': ['rounded-tl', 'rounded-tr'],\n 'rounded-r': ['rounded-tr', 'rounded-br'],\n 'rounded-b': ['rounded-br', 'rounded-bl'],\n 'rounded-l': ['rounded-tl', 'rounded-bl'],\n 'border-spacing': ['border-spacing-x', 'border-spacing-y'],\n 'border-w': ['border-w-s', 'border-w-e', 'border-w-t', 'border-w-r', 'border-w-b', 'border-w-l'],\n 'border-w-x': ['border-w-r', 'border-w-l'],\n 'border-w-y': ['border-w-t', 'border-w-b'],\n 'border-color': ['border-color-t', 'border-color-r', 'border-color-b', 'border-color-l'],\n 'border-color-x': ['border-color-r', 'border-color-l'],\n 'border-color-y': ['border-color-t', 'border-color-b'],\n 'scroll-m': ['scroll-mx', 'scroll-my', 'scroll-ms', 'scroll-me', 'scroll-mt', 'scroll-mr', 'scroll-mb', 'scroll-ml'],\n 'scroll-mx': ['scroll-mr', 'scroll-ml'],\n 'scroll-my': ['scroll-mt', 'scroll-mb'],\n 'scroll-p': ['scroll-px', 'scroll-py', 'scroll-ps', 'scroll-pe', 'scroll-pt', 'scroll-pr', 'scroll-pb', 'scroll-pl'],\n 'scroll-px': ['scroll-pr', 'scroll-pl'],\n 'scroll-py': ['scroll-pt', 'scroll-pb']\n },\n conflictingClassGroupModifiers: {\n 'font-size': ['leading']\n }\n };\n}\n\nexport { getDefaultConfig };\n//# sourceMappingURL=default-config.mjs.map\n","import validate from './validate.js';\n\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nvar byteToHex = [];\nfor (var i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n //\n // Note to future-self: No, you can't remove the `toLowerCase()` call.\n // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351\n return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n var uuid = unsafeStringify(arr, offset);\n // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexport default stringify;","import { createTailwindMerge } from './create-tailwind-merge.mjs';\nimport { getDefaultConfig } from './default-config.mjs';\n\nvar twMerge = /*#__PURE__*/createTailwindMerge(getDefaultConfig);\n\nexport { twMerge };\n//# sourceMappingURL=tw-merge.mjs.map\n","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\n\nvar getRandomValues;\nvar rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n return getRandomValues(rnds8);\n}","var randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nexport default {\n randomUUID\n};","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n options = options || {};\n var rnds = options.random || (options.rng || rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n offset = offset || 0;\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return unsafeStringify(rnds);\n}\nexport default v4;","import { type ClassValue, clsx } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n\nexport function isStringEmpty(str: string | null | undefined): boolean {\n return str === null || str === undefined || str.trim() === \"\";\n}\n\nexport function isStringNotEmpty(str: string | null | undefined): boolean {\n return !isStringEmpty(str);\n}\n\n// crypto.randomUUID() is only available secure environments (https). This is a fallback for unsecure environments.\nexport function uuid() {\n return uuidv4();\n}\n\nexport function toTitleCase(str: string) {\n return str.replace(/\\w\\S*/g, (text) => text.charAt(0).toUpperCase() + text.substring(1).toLowerCase());\n}\n\nexport function replaceAll(str: string, find: string, replace: string) {\n return str.replace(new RegExp(find, \"g\"), replace);\n}\n\nexport function camelCaseToTitleCase(str: string) {\n return str.replace(/([a-z])([A-Z])/g, \"$1 $2\").replace(/\\b\\w/g, (word) => word.toUpperCase());\n}\n","import type { GeneralTrackEvent, TrackEvent, BasicEvent } from \"@common/schemas/track\";\nimport { EventBuffer } from \"./EventBuffer\";\nimport invariant from \"ts-invariant\";\nimport { uuid } from \"../utils\";\n\nexport { BasicEvent };\n\nlet eventBuffer: EventBuffer | null = null;\n\nexport function initEventBuffer(apiBaseUrl: string, appId: string) {\n if (!eventBuffer) {\n eventBuffer = new EventBuffer(apiBaseUrl, appId);\n }\n}\n\nexport type TrackUser = { user_id?: string; user_traits?: any; anonymous_id?: string };\n\ntype BasicTrackFn = (eventData: E, user?: TrackUser) => void;\n\nexport const trackAnyEvent: BasicTrackFn = (eventData, user) => {\n invariant(eventBuffer, \"Event buffer not initialized\");\n\n try {\n const event: GeneralTrackEvent = {\n message_id: uuid() as string,\n timestamp: new Date().toISOString(),\n user_id: user?.user_id ?? null,\n user_traits: user?.user_traits ?? null,\n anonymous_id: user?.anonymous_id ?? null,\n event: eventData.event,\n type: \"track\" as const,\n properties: eventData.properties || {},\n context: {\n page: {\n path: location.pathname,\n search: location.search,\n title: document.title,\n url: location.href,\n },\n userAgentData: (navigator as any).userAgentData,\n userAgent: navigator.userAgent,\n locale: navigator.language,\n clientVersion: process.env.VERSION as unknown as string[],\n ...eventData.context,\n },\n };\n\n eventBuffer.push(event);\n } catch (e) {\n console.error(\"track error\", e);\n }\n};\n\n// This function is similar to trackAnyEvent, but has a stricter type and only allows known events\nexport const track: BasicTrackFn = trackAnyEvent;\n\nexport type { TrackEvent, TrackEvents } from \"@common/schemas/track\";\n","import { AllContexts } from \"../events/allEvents\";\nimport { globalEventBus } from \"../events/eventBus\";\nimport { initEventBuffer, track as trackFn, TrackUser } from \"../tracking/track\";\nimport { invariant } from \"ts-invariant\";\nimport { TrackEvent } from \"@common/schemas/track\";\nimport { log } from \"../log\";\n\ntype GetUserFn = () => { user_id?: string; user_traits?: any; anonymous_id?: string };\ntype TrackFn = typeof trackFn;\n\nexport interface TourAnalyticsCollectorInitParams {\n appId: string;\n apiBaseUrl: string;\n track?: TrackFn;\n getUser?: GetUserFn;\n}\n\nexport class TourAnalyticsCollector {\n static init({ appId, apiBaseUrl, track: _track, getUser }: TourAnalyticsCollectorInitParams) {\n initEventBuffer(apiBaseUrl, appId);\n let track = _track ?? trackFn;\n\n const safeTrack = (event: TrackEvent, user?: TrackUser) => {\n try {\n track(event, user);\n } catch (e) {\n log(\"Error tracking event\", e);\n }\n };\n\n globalEventBus.on(\n \"tourSessionManager.tourSessionStarted\",\n ({ context, payload: { reason, sessionId, startedAt } }) => {\n invariant(context.guide, \"Guide is not defined\");\n\n safeTrack(\n {\n event: \"tour_session_started\",\n properties: {\n guideId: context.guide.id,\n guideName: context.guide.title ?? \"Untitled\",\n tourSessionId: sessionId,\n reason,\n startedAt,\n },\n },\n getUser?.()\n );\n }\n );\n\n globalEventBus.on(\"tourSessionManager.tourSessionResumed\", ({ context, payload }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"tour_session_resumed\",\n properties: {\n guideId: context.guide.id,\n guideName: context.guide.title ?? \"Untitled\",\n tourSessionId: payload.sessionId,\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourPlayback.userEngaged\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"user_engaged\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourSessionManager.tourSessionExpired\", ({ context, payload }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"tour_session_expired\",\n properties: {\n guideId: context.guide.id,\n guideName: context.guide.title ?? \"Untitled\",\n tourSessionId: payload.sessionId,\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourSessionManager.tourSessionTerminated\", ({ context, payload }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"tour_session_terminated\",\n properties: {\n guideId: context.guide.id,\n guideName: context.guide.title ?? \"Untitled\",\n tourSessionId: payload.sessionId,\n reason: payload.reason,\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourPlayback.questionChoiceSelected\", ({ context, payload: { choiceId } }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"tour_question_choice_selected\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n choiceId: choiceId,\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"avatar.skipClicked\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"step_skip_clicked\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n avatarStatus: context.avatarStatus,\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"avatar.playClicked\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"play_clicked\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"avatar.pauseClicked\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"pause_clicked\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"avatar.replayClicked\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"step_replay_clicked\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"avatar.captionClicked\", ({ payload: { status }, context }) => {\n invariant(context.guide, \"Guide is not defined\");\n if (status) {\n safeTrack(\n {\n event: \"avatar_captions_enabled\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n return;\n }\n\n safeTrack(\n {\n event: \"avatar_captions_disabled\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"avatar.muteClicked\", ({ payload: { status }, context }) => {\n invariant(context.guide, \"Guide is not defined\");\n if (status) {\n safeTrack(\n {\n event: \"avatar_muted\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n return;\n }\n\n safeTrack(\n {\n event: \"avatar_unmuted\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"guideScheduler.userTargeted\", ({ payload: { guide } }) => {\n safeTrack(\n {\n event: \"user_targeted\",\n properties: {\n guideId: guide.id,\n guideName: guide.title ?? \"Untitled\",\n tourPlaybackVersion: guide.tour_playback?.version ?? \"unknown\",\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourLifecycle.tourStarted\", ({ payload: { guide } }) => {\n safeTrack(\n {\n event: \"guide_displayed\",\n properties: {\n guideId: guide.id,\n guideName: guide.title ?? \"Untitled\",\n tourPlaybackVersion: guide.tour_playback?.version ?? \"unknown\",\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourPlayback.finished\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"guide_finished\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n guideProgressPct: undefined,\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourPlayback.dismissed\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"guide_dismissed\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourPlayback.stepExecuted\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"guide_step_executed\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourPlayback.targetElementNotFound\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"guide_step_target_not_found\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourPlayback.userWanderedOff\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"user_wandered_off\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourPlayback.targetElementHighlighted\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"guide_target_element_highlighted\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourPlayback.suspended\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"guide_suspended\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"avatar.minimizeClicked\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"avatar_minimized\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"avatar.mediaError\", ({ context, payload }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"avatar_media_error\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n details: JSON.stringify(payload),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourPlayback.unsuspended\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"guide_unsuspended\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourPlayback.introStartTourClicked\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"guide_intro_start_tour_clicked\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourPlayback.introPostponeTourClicked\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"guide_intro_postpone_tour_clicked\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourPlayback.introCloseTourClicked\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"guide_intro_close_tour_clicked\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n\n globalEventBus.on(\"tourPlayback.feedbackClicked\", ({ context }) => {\n invariant(context.guide, \"Guide is not defined\");\n safeTrack(\n {\n event: \"guide_feedback_clicked\",\n properties: {\n ...getCommonPlaybackEventProperties(context),\n },\n },\n getUser?.()\n );\n });\n }\n}\n\nfunction getCommonPlaybackEventProperties(context: AllContexts) {\n invariant(context.guide, \"Guide is not defined\");\n return {\n guideId: context.guide.id,\n guideName: context.guide.title ?? \"Untitled\",\n stepId: context.stepId,\n stepType: context.stepType,\n stepIndex: context.stepIndex,\n sectionIndex: context.sectionIndex,\n stepOrder: context.stepOrder,\n totalSteps: context.totalSteps,\n totalSections: context.totalSections,\n totalSectionSteps: context.totalSectionSteps,\n flowKey: context.flowKey,\n time: Math.round(context.time),\n currentMediaDuration: Math.round(context.currentMediaDuration),\n tourPlaybackVersion: context.tourPlaybackVersion,\n guideProgressPct: context.tourProgress,\n tourSessionId: context.sessionId,\n };\n}\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n","import freeGlobal from './_freeGlobal.js';\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\nexport default root;\n","import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n","import Symbol from './_Symbol.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nexport default getRawTag;\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 nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nexport default baseGetTag;\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 != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\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) && baseGetTag(value) == symbolTag);\n}\n\nexport default isSymbol;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","/**\n * Checks if `value` is classified as an `Array` object.\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 array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","import Symbol from './_Symbol.js';\nimport arrayMap from './_arrayMap.js';\nimport isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n/**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nexport default baseToString;\n","/** Used to match a single whitespace character. */\nvar reWhitespace = /\\s/;\n\n/**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\nfunction trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n}\n\nexport default trimmedEndIndex;\n","import trimmedEndIndex from './_trimmedEndIndex.js';\n\n/** Used to match leading whitespace. */\nvar reTrimStart = /^\\s+/;\n\n/**\n * The base implementation of `_.trim`.\n *\n * @private\n * @param {string} string The string to trim.\n * @returns {string} Returns the trimmed string.\n */\nfunction baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n}\n\nexport default baseTrim;\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 != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","import baseTrim from './_baseTrim.js';\nimport isObject from './isObject.js';\nimport isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\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/**\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 = baseTrim(value);\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\nexport default toNumber;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\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 a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nexport default isFunction;\n","import root from './_root.js';\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nexport default coreJsData;\n","import coreJsData from './_coreJsData.js';\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nexport default isMasked;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","import isFunction from './isFunction.js';\nimport isMasked from './_isMasked.js';\nimport isObject from './isObject.js';\nimport toSource from './_toSource.js';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nexport default baseIsNative;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","import baseIsNative from './_baseIsNative.js';\nimport getValue from './_getValue.js';\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nexport default getNative;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nexport default WeakMap;\n","import isObject from './isObject.js';\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nvar baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n}());\n\nexport default baseCreate;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","import getNative from './_getNative.js';\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nexport default defineProperty;\n","import constant from './constant.js';\nimport defineProperty from './_defineProperty.js';\nimport identity from './identity.js';\n\n/**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n};\n\nexport default baseSetToString;\n","import baseSetToString from './_baseSetToString.js';\nimport shortOut from './_shortOut.js';\n\n/**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar setToString = shortOut(baseSetToString);\n\nexport default setToString;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","import defineProperty from './_defineProperty.js';\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nexport default baseAssignValue;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","import baseAssignValue from './_baseAssignValue.js';\nimport eq from './eq.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nexport default assignValue;\n","import assignValue from './_assignValue.js';\nimport baseAssignValue from './_baseAssignValue.js';\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n}\n\nexport default copyObject;\n","import apply from './_apply.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\nfunction overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n}\n\nexport default overRest;\n","import identity from './identity.js';\nimport overRest from './_overRest.js';\nimport setToString from './_setToString.js';\n\n/**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\nfunction baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n}\n\nexport default baseRest;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\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 valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\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 array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nexport default isArrayLike;\n","import eq from './eq.js';\nimport isArrayLike from './isArrayLike.js';\nimport isIndex from './_isIndex.js';\nimport isObject from './isObject.js';\n\n/**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\nfunction isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n}\n\nexport default isIterateeCall;\n","import baseRest from './_baseRest.js';\nimport isIterateeCall from './_isIterateeCall.js';\n\n/**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\nfunction createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n}\n\nexport default createAssigner;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nexport default baseIsArguments;\n","import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\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 `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nexport default isArguments;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n","import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nexport default baseIsTypedArray;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nexport default nodeUtil;\n","import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nexport default isTypedArray;\n","import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default arrayLikeKeys;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n","import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeys;\n","import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nexport default keys;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","import isObject from './isObject.js';\nimport isPrototype from './_isPrototype.js';\nimport nativeKeysIn from './_nativeKeysIn.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeysIn;\n","import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeysIn from './_baseKeysIn.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nexport default keysIn;\n","import isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\n\n/** Used to match property names within property paths. */\nvar reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/;\n\n/**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\nfunction isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n}\n\nexport default isKey;\n","import getNative from './_getNative.js';\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nexport default nativeCreate;\n","import nativeCreate from './_nativeCreate.js';\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nexport default hashClear;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nexport default hashGet;\n","import nativeCreate from './_nativeCreate.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nexport default hashHas;\n","import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nexport default hashSet;\n","import hashClear from './_hashClear.js';\nimport hashDelete from './_hashDelete.js';\nimport hashGet from './_hashGet.js';\nimport hashHas from './_hashHas.js';\nimport hashSet from './_hashSet.js';\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nexport default Hash;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","import eq from './eq.js';\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nexport default assocIndexOf;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nexport default listCacheDelete;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nexport default listCacheGet;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nexport default listCacheHas;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nexport default listCacheSet;\n","import listCacheClear from './_listCacheClear.js';\nimport listCacheDelete from './_listCacheDelete.js';\nimport listCacheGet from './_listCacheGet.js';\nimport listCacheHas from './_listCacheHas.js';\nimport listCacheSet from './_listCacheSet.js';\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nexport default ListCache;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nexport default Map;\n","import Hash from './_Hash.js';\nimport ListCache from './_ListCache.js';\nimport Map from './_Map.js';\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nexport default mapCacheClear;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","import isKeyable from './_isKeyable.js';\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nexport default getMapData;\n","import getMapData from './_getMapData.js';\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default mapCacheDelete;\n","import getMapData from './_getMapData.js';\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nexport default mapCacheGet;\n","import getMapData from './_getMapData.js';\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nexport default mapCacheHas;\n","import getMapData from './_getMapData.js';\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nexport default mapCacheSet;\n","import mapCacheClear from './_mapCacheClear.js';\nimport mapCacheDelete from './_mapCacheDelete.js';\nimport mapCacheGet from './_mapCacheGet.js';\nimport mapCacheHas from './_mapCacheHas.js';\nimport mapCacheSet from './_mapCacheSet.js';\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nexport default MapCache;\n","import MapCache from './_MapCache.js';\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\nfunction memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n}\n\n// Expose `MapCache`.\nmemoize.Cache = MapCache;\n\nexport default memoize;\n","import memoize from './memoize.js';\n\n/** Used as the maximum memoize cache size. */\nvar MAX_MEMOIZE_SIZE = 500;\n\n/**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\nfunction memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n}\n\nexport default memoizeCapped;\n","import memoizeCapped from './_memoizeCapped.js';\n\n/** Used to match property names within property paths. */\nvar rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n/** Used to match backslashes in property paths. */\nvar reEscapeChar = /\\\\(\\\\)?/g;\n\n/**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\nvar stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n});\n\nexport default stringToPath;\n","import baseToString from './_baseToString.js';\n\n/**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\nfunction toString(value) {\n return value == null ? '' : baseToString(value);\n}\n\nexport default toString;\n","import isArray from './isArray.js';\nimport isKey from './_isKey.js';\nimport stringToPath from './_stringToPath.js';\nimport toString from './toString.js';\n\n/**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\nfunction castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n}\n\nexport default castPath;\n","import isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\nfunction toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nexport default toKey;\n","import castPath from './_castPath.js';\nimport toKey from './_toKey.js';\n\n/**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\nfunction baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n}\n\nexport default baseGet;\n","import baseGet from './_baseGet.js';\n\n/**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\nfunction get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n}\n\nexport default get;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","import Symbol from './_Symbol.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\n\n/** Built-in value references. */\nvar spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;\n\n/**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\nfunction isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n}\n\nexport default isFlattenable;\n","import arrayPush from './_arrayPush.js';\nimport isFlattenable from './_isFlattenable.js';\n\n/**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\nfunction baseFlatten(array, depth, predicate, isStrict, result) {\n var index = -1,\n length = array.length;\n\n predicate || (predicate = isFlattenable);\n result || (result = []);\n\n while (++index < length) {\n var value = array[index];\n if (depth > 0 && predicate(value)) {\n if (depth > 1) {\n // Recursively flatten arrays (susceptible to call stack limits).\n baseFlatten(value, depth - 1, predicate, isStrict, result);\n } else {\n arrayPush(result, value);\n }\n } else if (!isStrict) {\n result[result.length] = value;\n }\n }\n return result;\n}\n\nexport default baseFlatten;\n","import overArg from './_overArg.js';\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nexport default getPrototype;\n","import baseGetTag from './_baseGetTag.js';\nimport getPrototype from './_getPrototype.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n}\n\nexport default isPlainObject;\n","import ListCache from './_ListCache.js';\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nexport default stackClear;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","import ListCache from './_ListCache.js';\nimport Map from './_Map.js';\nimport MapCache from './_MapCache.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nexport default stackSet;\n","import ListCache from './_ListCache.js';\nimport stackClear from './_stackClear.js';\nimport stackDelete from './_stackDelete.js';\nimport stackGet from './_stackGet.js';\nimport stackHas from './_stackHas.js';\nimport stackSet from './_stackSet.js';\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nexport default Stack;\n","import root from './_root.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n}\n\nexport default cloneBuffer;\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","import arrayFilter from './_arrayFilter.js';\nimport stubArray from './stubArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nexport default getSymbols;\n","import arrayPush from './_arrayPush.js';\nimport getPrototype from './_getPrototype.js';\nimport getSymbols from './_getSymbols.js';\nimport stubArray from './stubArray.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n};\n\nexport default getSymbolsIn;\n","import arrayPush from './_arrayPush.js';\nimport isArray from './isArray.js';\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nexport default baseGetAllKeys;\n","import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbols from './_getSymbols.js';\nimport keys from './keys.js';\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nexport default getAllKeys;\n","import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbolsIn from './_getSymbolsIn.js';\nimport keysIn from './keysIn.js';\n\n/**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n}\n\nexport default getAllKeysIn;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nexport default DataView;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nexport default Promise;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nexport default Set;\n","import DataView from './_DataView.js';\nimport Map from './_Map.js';\nimport Promise from './_Promise.js';\nimport Set from './_Set.js';\nimport WeakMap from './_WeakMap.js';\nimport baseGetTag from './_baseGetTag.js';\nimport toSource from './_toSource.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nexport default getTag;\n","import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\n","import Uint8Array from './_Uint8Array.js';\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\nexport default cloneArrayBuffer;\n","import cloneArrayBuffer from './_cloneArrayBuffer.js';\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nexport default cloneTypedArray;\n","import baseCreate from './_baseCreate.js';\nimport getPrototype from './_getPrototype.js';\nimport isPrototype from './_isPrototype.js';\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\nexport default initCloneObject;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n","import MapCache from './_MapCache.js';\nimport setCacheAdd from './_setCacheAdd.js';\nimport setCacheHas from './_setCacheHas.js';\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nexport default SetCache;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n","import SetCache from './_SetCache.js';\nimport arraySome from './_arraySome.js';\nimport cacheHas from './_cacheHas.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nexport default equalArrays;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n","import Symbol from './_Symbol.js';\nimport Uint8Array from './_Uint8Array.js';\nimport eq from './eq.js';\nimport equalArrays from './_equalArrays.js';\nimport mapToArray from './_mapToArray.js';\nimport setToArray from './_setToArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nexport default equalByTag;\n","import getAllKeys from './_getAllKeys.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nexport default equalObjects;\n","import Stack from './_Stack.js';\nimport equalArrays from './_equalArrays.js';\nimport equalByTag from './_equalByTag.js';\nimport equalObjects from './_equalObjects.js';\nimport getTag from './_getTag.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nexport default baseIsEqualDeep;\n","import baseIsEqualDeep from './_baseIsEqualDeep.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nexport default baseIsEqual;\n","import Stack from './_Stack.js';\nimport baseIsEqual from './_baseIsEqual.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\nfunction baseIsMatch(object, source, matchData, customizer) {\n var index = matchData.length,\n length = index,\n noCustomizer = !customizer;\n\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (index--) {\n var data = matchData[index];\n if ((noCustomizer && data[2])\n ? data[1] !== object[data[0]]\n : !(data[0] in object)\n ) {\n return false;\n }\n }\n while (++index < length) {\n data = matchData[index];\n var key = data[0],\n objValue = object[key],\n srcValue = data[1];\n\n if (noCustomizer && data[2]) {\n if (objValue === undefined && !(key in object)) {\n return false;\n }\n } else {\n var stack = new Stack;\n if (customizer) {\n var result = customizer(objValue, srcValue, key, object, source, stack);\n }\n if (!(result === undefined\n ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n : result\n )) {\n return false;\n }\n }\n }\n return true;\n}\n\nexport default baseIsMatch;\n","import isObject from './isObject.js';\n\n/**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\nfunction isStrictComparable(value) {\n return value === value && !isObject(value);\n}\n\nexport default isStrictComparable;\n","import isStrictComparable from './_isStrictComparable.js';\nimport keys from './keys.js';\n\n/**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\nfunction getMatchData(object) {\n var result = keys(object),\n length = result.length;\n\n while (length--) {\n var key = result[length],\n value = object[key];\n\n result[length] = [key, value, isStrictComparable(value)];\n }\n return result;\n}\n\nexport default getMatchData;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nexport default matchesStrictComparable;\n","import baseIsMatch from './_baseIsMatch.js';\nimport getMatchData from './_getMatchData.js';\nimport matchesStrictComparable from './_matchesStrictComparable.js';\n\n/**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatches(source) {\n var matchData = getMatchData(source);\n if (matchData.length == 1 && matchData[0][2]) {\n return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n }\n return function(object) {\n return object === source || baseIsMatch(object, source, matchData);\n };\n}\n\nexport default baseMatches;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n","import castPath from './_castPath.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isIndex from './_isIndex.js';\nimport isLength from './isLength.js';\nimport toKey from './_toKey.js';\n\n/**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\nfunction hasPath(object, path, hasFunc) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n result = false;\n\n while (++index < length) {\n var key = toKey(path[index]);\n if (!(result = object != null && hasFunc(object, key))) {\n break;\n }\n object = object[key];\n }\n if (result || ++index != length) {\n return result;\n }\n length = object == null ? 0 : object.length;\n return !!length && isLength(length) && isIndex(key, length) &&\n (isArray(object) || isArguments(object));\n}\n\nexport default hasPath;\n","import baseHasIn from './_baseHasIn.js';\nimport hasPath from './_hasPath.js';\n\n/**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\nfunction hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n}\n\nexport default hasIn;\n","import baseIsEqual from './_baseIsEqual.js';\nimport get from './get.js';\nimport hasIn from './hasIn.js';\nimport isKey from './_isKey.js';\nimport isStrictComparable from './_isStrictComparable.js';\nimport matchesStrictComparable from './_matchesStrictComparable.js';\nimport toKey from './_toKey.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatchesProperty(path, srcValue) {\n if (isKey(path) && isStrictComparable(srcValue)) {\n return matchesStrictComparable(toKey(path), srcValue);\n }\n return function(object) {\n var objValue = get(object, path);\n return (objValue === undefined && objValue === srcValue)\n ? hasIn(object, path)\n : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n };\n}\n\nexport default baseMatchesProperty;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n","import baseGet from './_baseGet.js';\n\n/**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n}\n\nexport default basePropertyDeep;\n","import baseProperty from './_baseProperty.js';\nimport basePropertyDeep from './_basePropertyDeep.js';\nimport isKey from './_isKey.js';\nimport toKey from './_toKey.js';\n\n/**\n * Creates a function that returns the value at `path` of a given object.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n * @example\n *\n * var objects = [\n * { 'a': { 'b': 2 } },\n * { 'a': { 'b': 1 } }\n * ];\n *\n * _.map(objects, _.property('a.b'));\n * // => [2, 1]\n *\n * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');\n * // => [1, 2]\n */\nfunction property(path) {\n return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);\n}\n\nexport default property;\n","import baseMatches from './_baseMatches.js';\nimport baseMatchesProperty from './_baseMatchesProperty.js';\nimport identity from './identity.js';\nimport isArray from './isArray.js';\nimport property from './property.js';\n\n/**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\nfunction baseIteratee(value) {\n // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n if (typeof value == 'function') {\n return value;\n }\n if (value == null) {\n return identity;\n }\n if (typeof value == 'object') {\n return isArray(value)\n ? baseMatchesProperty(value[0], value[1])\n : baseMatches(value);\n }\n return property(value);\n}\n\nexport default baseIteratee;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","import createBaseFor from './_createBaseFor.js';\n\n/**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\nvar baseFor = createBaseFor();\n\nexport default baseFor;\n","import baseFor from './_baseFor.js';\nimport keys from './keys.js';\n\n/**\n * The base implementation of `_.forOwn` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\nfunction baseForOwn(object, iteratee) {\n return object && baseFor(object, iteratee, keys);\n}\n\nexport default baseForOwn;\n","import isArrayLike from './isArrayLike.js';\n\n/**\n * Creates a `baseEach` or `baseEachRight` function.\n *\n * @private\n * @param {Function} eachFunc The function to iterate over a collection.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseEach(eachFunc, fromRight) {\n return function(collection, iteratee) {\n if (collection == null) {\n return collection;\n }\n if (!isArrayLike(collection)) {\n return eachFunc(collection, iteratee);\n }\n var length = collection.length,\n index = fromRight ? length : -1,\n iterable = Object(collection);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (iteratee(iterable[index], index, iterable) === false) {\n break;\n }\n }\n return collection;\n };\n}\n\nexport default createBaseEach;\n","import baseForOwn from './_baseForOwn.js';\nimport createBaseEach from './_createBaseEach.js';\n\n/**\n * The base implementation of `_.forEach` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\nvar baseEach = createBaseEach(baseForOwn);\n\nexport default baseEach;\n","import root from './_root.js';\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\nexport default now;\n","import isObject from './isObject.js';\nimport now from './now.js';\nimport toNumber from './toNumber.js';\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\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 * 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 timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\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 clearTimeout(timerId);\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\nexport default debounce;\n","import baseAssignValue from './_baseAssignValue.js';\nimport eq from './eq.js';\n\n/**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nexport default assignMergeValue;\n","import isArrayLike from './isArrayLike.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an 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 an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\nexport default isArrayLikeObject;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","import copyObject from './_copyObject.js';\nimport keysIn from './keysIn.js';\n\n/**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\nfunction toPlainObject(value) {\n return copyObject(value, keysIn(value));\n}\n\nexport default toPlainObject;\n","import assignMergeValue from './_assignMergeValue.js';\nimport cloneBuffer from './_cloneBuffer.js';\nimport cloneTypedArray from './_cloneTypedArray.js';\nimport copyArray from './_copyArray.js';\nimport initCloneObject from './_initCloneObject.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isArrayLikeObject from './isArrayLikeObject.js';\nimport isBuffer from './isBuffer.js';\nimport isFunction from './isFunction.js';\nimport isObject from './isObject.js';\nimport isPlainObject from './isPlainObject.js';\nimport isTypedArray from './isTypedArray.js';\nimport safeGet from './_safeGet.js';\nimport toPlainObject from './toPlainObject.js';\n\n/**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n}\n\nexport default baseMergeDeep;\n","import Stack from './_Stack.js';\nimport assignMergeValue from './_assignMergeValue.js';\nimport baseFor from './_baseFor.js';\nimport baseMergeDeep from './_baseMergeDeep.js';\nimport isObject from './isObject.js';\nimport keysIn from './keysIn.js';\nimport safeGet from './_safeGet.js';\n\n/**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n}\n\nexport default baseMerge;\n","import baseEach from './_baseEach.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * The base implementation of `_.map` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction baseMap(collection, iteratee) {\n var index = -1,\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value, key, collection) {\n result[++index] = iteratee(value, key, collection);\n });\n return result;\n}\n\nexport default baseMap;\n","import baseIsEqual from './_baseIsEqual.js';\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\nexport default isEqual;\n","import baseMerge from './_baseMerge.js';\nimport createAssigner from './_createAssigner.js';\n\n/**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\nvar merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n});\n\nexport default merge;\n","import assignValue from './_assignValue.js';\nimport castPath from './_castPath.js';\nimport isIndex from './_isIndex.js';\nimport isObject from './isObject.js';\nimport toKey from './_toKey.js';\n\n/**\n * The base implementation of `_.set`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\nfunction baseSet(object, path, value, customizer) {\n if (!isObject(object)) {\n return object;\n }\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n lastIndex = length - 1,\n nested = object;\n\n while (nested != null && ++index < length) {\n var key = toKey(path[index]),\n newValue = value;\n\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return object;\n }\n\n if (index != lastIndex) {\n var objValue = nested[key];\n newValue = customizer ? customizer(objValue, key, nested) : undefined;\n if (newValue === undefined) {\n newValue = isObject(objValue)\n ? objValue\n : (isIndex(path[index + 1]) ? [] : {});\n }\n }\n assignValue(nested, key, newValue);\n nested = nested[key];\n }\n return object;\n}\n\nexport default baseSet;\n","import baseGet from './_baseGet.js';\nimport baseSet from './_baseSet.js';\nimport castPath from './_castPath.js';\n\n/**\n * The base implementation of `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\nfunction basePickBy(object, paths, predicate) {\n var index = -1,\n length = paths.length,\n result = {};\n\n while (++index < length) {\n var path = paths[index],\n value = baseGet(object, path);\n\n if (predicate(value, path)) {\n baseSet(result, castPath(path, object), value);\n }\n }\n return result;\n}\n\nexport default basePickBy;\n","import arrayMap from './_arrayMap.js';\nimport baseIteratee from './_baseIteratee.js';\nimport basePickBy from './_basePickBy.js';\nimport getAllKeysIn from './_getAllKeysIn.js';\n\n/**\n * Creates an object composed of the `object` properties `predicate` returns\n * truthy for. The predicate is invoked with two arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pickBy(object, _.isNumber);\n * // => { 'a': 1, 'c': 3 }\n */\nfunction pickBy(object, predicate) {\n if (object == null) {\n return {};\n }\n var props = arrayMap(getAllKeysIn(object), function(prop) {\n return [prop];\n });\n predicate = baseIteratee(predicate);\n return basePickBy(object, props, function(value, path) {\n return predicate(value, path[0]);\n });\n}\n\nexport default pickBy;\n","/**\n * The base implementation of `_.sortBy` which uses `comparer` to define the\n * sort order of `array` and replaces criteria objects with their corresponding\n * values.\n *\n * @private\n * @param {Array} array The array to sort.\n * @param {Function} comparer The function to define sort order.\n * @returns {Array} Returns `array`.\n */\nfunction baseSortBy(array, comparer) {\n var length = array.length;\n\n array.sort(comparer);\n while (length--) {\n array[length] = array[length].value;\n }\n return array;\n}\n\nexport default baseSortBy;\n","import isSymbol from './isSymbol.js';\n\n/**\n * Compares values to sort them in ascending order.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {number} Returns the sort order indicator for `value`.\n */\nfunction compareAscending(value, other) {\n if (value !== other) {\n var valIsDefined = value !== undefined,\n valIsNull = value === null,\n valIsReflexive = value === value,\n valIsSymbol = isSymbol(value);\n\n var othIsDefined = other !== undefined,\n othIsNull = other === null,\n othIsReflexive = other === other,\n othIsSymbol = isSymbol(other);\n\n if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||\n (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||\n (valIsNull && othIsDefined && othIsReflexive) ||\n (!valIsDefined && othIsReflexive) ||\n !valIsReflexive) {\n return 1;\n }\n if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||\n (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||\n (othIsNull && valIsDefined && valIsReflexive) ||\n (!othIsDefined && valIsReflexive) ||\n !othIsReflexive) {\n return -1;\n }\n }\n return 0;\n}\n\nexport default compareAscending;\n","import compareAscending from './_compareAscending.js';\n\n/**\n * Used by `_.orderBy` to compare multiple properties of a value to another\n * and stable sort them.\n *\n * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,\n * specify an order of \"desc\" for descending or \"asc\" for ascending sort order\n * of corresponding values.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {boolean[]|string[]} orders The order to sort by for each property.\n * @returns {number} Returns the sort order indicator for `object`.\n */\nfunction compareMultiple(object, other, orders) {\n var index = -1,\n objCriteria = object.criteria,\n othCriteria = other.criteria,\n length = objCriteria.length,\n ordersLength = orders.length;\n\n while (++index < length) {\n var result = compareAscending(objCriteria[index], othCriteria[index]);\n if (result) {\n if (index >= ordersLength) {\n return result;\n }\n var order = orders[index];\n return result * (order == 'desc' ? -1 : 1);\n }\n }\n // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications\n // that causes it, under certain circumstances, to provide the same value for\n // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247\n // for more details.\n //\n // This also ensures a stable sort in V8 and other engines.\n // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.\n return object.index - other.index;\n}\n\nexport default compareMultiple;\n","import arrayMap from './_arrayMap.js';\nimport baseGet from './_baseGet.js';\nimport baseIteratee from './_baseIteratee.js';\nimport baseMap from './_baseMap.js';\nimport baseSortBy from './_baseSortBy.js';\nimport baseUnary from './_baseUnary.js';\nimport compareMultiple from './_compareMultiple.js';\nimport identity from './identity.js';\nimport isArray from './isArray.js';\n\n/**\n * The base implementation of `_.orderBy` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.\n * @param {string[]} orders The sort orders of `iteratees`.\n * @returns {Array} Returns the new sorted array.\n */\nfunction baseOrderBy(collection, iteratees, orders) {\n if (iteratees.length) {\n iteratees = arrayMap(iteratees, function(iteratee) {\n if (isArray(iteratee)) {\n return function(value) {\n return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);\n }\n }\n return iteratee;\n });\n } else {\n iteratees = [identity];\n }\n\n var index = -1;\n iteratees = arrayMap(iteratees, baseUnary(baseIteratee));\n\n var result = baseMap(collection, function(value, key, collection) {\n var criteria = arrayMap(iteratees, function(iteratee) {\n return iteratee(value);\n });\n return { 'criteria': criteria, 'index': ++index, 'value': value };\n });\n\n return baseSortBy(result, function(object, other) {\n return compareMultiple(object, other, orders);\n });\n}\n\nexport default baseOrderBy;\n","import baseFlatten from './_baseFlatten.js';\nimport baseOrderBy from './_baseOrderBy.js';\nimport baseRest from './_baseRest.js';\nimport isIterateeCall from './_isIterateeCall.js';\n\n/**\n * Creates an array of elements, sorted in ascending order by the results of\n * running each element in a collection thru each iteratee. This method\n * performs a stable sort, that is, it preserves the original sort order of\n * equal elements. The iteratees are invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {...(Function|Function[])} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 30 },\n * { 'user': 'barney', 'age': 34 }\n * ];\n *\n * _.sortBy(users, [function(o) { return o.user; }]);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]\n *\n * _.sortBy(users, ['user', 'age']);\n * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]\n */\nvar sortBy = baseRest(function(collection, iteratees) {\n if (collection == null) {\n return [];\n }\n var length = iteratees.length;\n if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {\n iteratees = [];\n } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {\n iteratees = [iteratees[0]];\n }\n return baseOrderBy(collection, baseFlatten(iteratees, 1), []);\n});\n\nexport default sortBy;\n","import debounce from './debounce.js';\nimport isObject from './isObject.js';\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a throttled function that only invokes `func` at most once per\n * every `wait` milliseconds. The throttled function comes with a `cancel`\n * method to cancel delayed `func` invocations and a `flush` method to\n * immediately invoke them. Provide `options` to indicate whether `func`\n * should be invoked on the leading and/or trailing edge of the `wait`\n * timeout. The `func` is invoked with the last arguments provided to the\n * throttled function. Subsequent calls to the throttled function return the\n * result of the last `func` 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 throttled 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 `_.throttle` and `_.debounce`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to throttle.\n * @param {number} [wait=0] The number of milliseconds to throttle invocations to.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=true]\n * Specify invoking on the leading edge of the timeout.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new throttled function.\n * @example\n *\n * // Avoid excessively updating the position while scrolling.\n * jQuery(window).on('scroll', _.throttle(updatePosition, 100));\n *\n * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.\n * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });\n * jQuery(element).on('click', throttled);\n *\n * // Cancel the trailing throttled invocation.\n * jQuery(window).on('popstate', throttled.cancel);\n */\nfunction throttle(func, wait, options) {\n var leading = true,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (isObject(options)) {\n leading = 'leading' in options ? !!options.leading : leading;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n return debounce(func, wait, {\n 'leading': leading,\n 'maxWait': wait,\n 'trailing': trailing\n });\n}\n\nexport default throttle;\n","export const isRunningInIframe = () => {\n return window.location !== window.parent.location;\n};\n\nexport const getWindow = () => {\n return isRunningInIframe() ? window.parent : window;\n};\n\nexport const getCurrentPath = () => {\n return getWindow().location.pathname;\n};\n\nexport const navigateTo = (url?: URL | string | null) => {\n getWindow().history.pushState({}, \"\", url);\n getWindow().location.reload();\n};\n\nexport const navigateToPath = (url?: string) => {\n if (url) {\n getWindow().location.href = url;\n }\n};\n\nexport const openSameTab = (url?: URL | string) => {\n if (!url) return;\n getWindow().location.href = url.toString();\n};\n\nexport const openNewTab = (url?: URL | string) => {\n if (!url) return;\n getWindow().open(url, \"_blank\");\n};\n\nexport const reloadWindow = () => {\n getWindow().location.reload();\n};\n\nexport const getUrl = () => {\n const win = getWindow();\n if (win.location.hash) {\n return getUrlWithoutParams() + win.location.search + win.location.hash;\n }\n return getUrlWithoutParams() + win.location.search;\n};\n\nexport const getUrlWithoutParams = () => {\n const win = getWindow();\n return win.location.origin + win.location.pathname;\n};\n\nexport const isUrlEqualsToCurrentUrl = (url: string) => {\n return stripPreviewQueryParams(getUrl()) === stripPreviewQueryParams(url);\n};\n\nexport const stripPreviewQueryParams = (url: string) => {\n if (!url || url === \"\") return url;\n try {\n const urlObj = new URL(url);\n urlObj.searchParams.delete(\"pyne-guide-id\");\n const result = urlObj.toString();\n return result;\n } catch (e) {\n console.error(\"Error parsing URL:\", e);\n return url;\n }\n};\n\nexport const openNewWindow = (url: string, width?: number, height?: number) => {\n var windowName = \"pyneWindow\" + Date.now();\n\n const windowWidth = window.screen.width;\n const windowHeight = window.screen.height;\n\n const popupWidth = width || windowWidth * 0.5;\n const popupHeight = height || windowHeight * 0.8;\n\n const left = windowWidth - popupWidth - 10;\n const top = (windowHeight - popupHeight) / 2;\n\n const features = `toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width=${popupWidth}, height=${popupHeight}, top=${top}, left=${left}`;\n\n getWindow().open(url, windowName, features);\n};\n","import { action, extendObservable, observable, _allowStateChanges, createAtom, computed, observe, makeObservable, runInAction, keys, isObservableArray, isObservableMap, isComputed, isObservableObject, $mobx, isComputedProp, _getAdministration, getAtom, isAction, autorun, _isComputingDerivation, onBecomeUnobserved, entries, values, transaction, reaction, ObservableMap, _getGlobalState } from 'mobx';\n\nvar NOOP = function () { };\r\nvar IDENTITY = function (_) { return _; };\r\nfunction fail(message) {\r\n throw new Error(\"[mobx-utils] \" + message);\r\n}\r\nfunction invariant(cond, message) {\r\n if (message === void 0) { message = \"Illegal state\"; }\r\n if (!cond)\r\n fail(message);\r\n}\r\nfunction addHiddenProp(object, propName, value) {\r\n Object.defineProperty(object, propName, {\r\n enumerable: false,\r\n writable: true,\r\n configurable: true,\r\n value: value,\r\n });\r\n}\r\nvar deepFields = function (x) {\r\n return (x &&\r\n x !== Object.prototype &&\r\n Object.getOwnPropertyNames(x).concat(deepFields(Object.getPrototypeOf(x)) || []));\r\n};\r\nvar distinctDeepFields = function (x) {\r\n var deepFieldsIndistinct = deepFields(x);\r\n var deepFieldsDistinct = deepFieldsIndistinct.filter(function (item, index) { return deepFieldsIndistinct.indexOf(item) === index; });\r\n return deepFieldsDistinct;\r\n};\r\nvar getAllMethodsAndProperties = function (x) {\r\n return distinctDeepFields(x).filter(function (name) { return name !== \"constructor\" && !~name.indexOf(\"__\"); });\r\n};\n\nvar PENDING = \"pending\";\r\nvar FULFILLED = \"fulfilled\";\r\nvar REJECTED = \"rejected\";\r\nfunction caseImpl(handlers) {\r\n switch (this.state) {\r\n case PENDING:\r\n return handlers.pending && handlers.pending(this.value);\r\n case REJECTED:\r\n return handlers.rejected && handlers.rejected(this.value);\r\n case FULFILLED:\r\n return handlers.fulfilled ? handlers.fulfilled(this.value) : this.value;\r\n }\r\n}\r\n/**\r\n * `fromPromise` takes a Promise, extends it with 2 observable properties that track\r\n * the status of the promise and returns it. The returned object has the following observable properties:\r\n * - `value`: either the initial value, the value the Promise resolved to, or the value the Promise was rejected with. use `.state` if you need to be able to tell the difference.\r\n * - `state`: one of `\"pending\"`, `\"fulfilled\"` or `\"rejected\"`\r\n *\r\n * And the following methods:\r\n * - `case({fulfilled, rejected, pending})`: maps over the result using the provided handlers, or returns `undefined` if a handler isn't available for the current promise state.\r\n *\r\n * The returned object implements `PromiseLike`, so you can chain additional `Promise` handlers using `then`. You may also use it with `await` in `async` functions.\r\n *\r\n * Note that the status strings are available as constants:\r\n * `mobxUtils.PENDING`, `mobxUtils.REJECTED`, `mobxUtil.FULFILLED`\r\n *\r\n * fromPromise takes an optional second argument, a previously created `fromPromise` based observable.\r\n * This is useful to replace one promise based observable with another, without going back to an intermediate\r\n * \"pending\" promise state while fetching data. For example:\r\n *\r\n * @example\r\n * \\@observer\r\n * class SearchResults extends React.Component {\r\n * \\@observable.ref searchResults\r\n *\r\n * componentDidUpdate(nextProps) {\r\n * if (nextProps.query !== this.props.query)\r\n * this.searchResults = fromPromise(\r\n * window.fetch(\"/search?q=\" + nextProps.query),\r\n * // by passing, we won't render a pending state if we had a successful search query before\r\n * // rather, we will keep showing the previous search results, until the new promise resolves (or rejects)\r\n * this.searchResults\r\n * )\r\n * }\r\n *\r\n * render() {\r\n * return this.searchResults.case({\r\n * pending: (staleValue) => {\r\n * return staleValue || \"searching\" // <- value might set to previous results while the promise is still pending\r\n * },\r\n * fulfilled: (value) => {\r\n * return value // the fresh results\r\n * },\r\n * rejected: (error) => {\r\n * return \"Oops: \" + error\r\n * }\r\n * })\r\n * }\r\n * }\r\n *\r\n * Observable promises can be created immediately in a certain state using\r\n * `fromPromise.reject(reason)` or `fromPromise.resolve(value?)`.\r\n * The main advantage of `fromPromise.resolve(value)` over `fromPromise(Promise.resolve(value))` is that the first _synchronously_ starts in the desired state.\r\n *\r\n * It is possible to directly create a promise using a resolve, reject function:\r\n * `fromPromise((resolve, reject) => setTimeout(() => resolve(true), 1000))`\r\n *\r\n * @example\r\n * const fetchResult = fromPromise(fetch(\"http://someurl\"))\r\n *\r\n * // combine with when..\r\n * when(\r\n * () => fetchResult.state !== \"pending\",\r\n * () => {\r\n * console.log(\"Got \", fetchResult.value)\r\n * }\r\n * )\r\n *\r\n * // or a mobx-react component..\r\n * const myComponent = observer(({ fetchResult }) => {\r\n * switch(fetchResult.state) {\r\n * case \"pending\": return
Loading...
\r\n * case \"rejected\": return
Ooops... {fetchResult.value}
\r\n * case \"fulfilled\": return
Gotcha: {fetchResult.value}
\r\n * }\r\n * })\r\n *\r\n * // or using the case method instead of switch:\r\n *\r\n * const myComponent = observer(({ fetchResult }) =>\r\n * fetchResult.case({\r\n * pending: () =>
Loading...
,\r\n * rejected: error =>
Ooops.. {error}
,\r\n * fulfilled: value =>
Gotcha: {value}
,\r\n * }))\r\n *\r\n * // chain additional handler(s) to the resolve/reject:\r\n *\r\n * fetchResult.then(\r\n * (result) => doSomeTransformation(result),\r\n * (rejectReason) => console.error('fetchResult was rejected, reason: ' + rejectReason)\r\n * ).then(\r\n * (transformedResult) => console.log('transformed fetchResult: ' + transformedResult)\r\n * )\r\n *\r\n * @param origPromise The promise which will be observed\r\n * @param oldPromise The previously observed promise\r\n * @returns origPromise with added properties and methods described above.\r\n */\r\nfunction fromPromise(origPromise, oldPromise) {\r\n invariant(arguments.length <= 2, \"fromPromise expects up to two arguments\");\r\n invariant(typeof origPromise === \"function\" ||\r\n (typeof origPromise === \"object\" &&\r\n origPromise &&\r\n typeof origPromise.then === \"function\"), \"Please pass a promise or function to fromPromise\");\r\n if (origPromise.isPromiseBasedObservable === true)\r\n return origPromise;\r\n if (typeof origPromise === \"function\") {\r\n // If it is a (reject, resolve function, wrap it)\r\n origPromise = new Promise(origPromise);\r\n }\r\n var promise = origPromise;\r\n origPromise.then(action(\"observableFromPromise-resolve\", function (value) {\r\n promise.value = value;\r\n promise.state = FULFILLED;\r\n }), action(\"observableFromPromise-reject\", function (reason) {\r\n promise.value = reason;\r\n promise.state = REJECTED;\r\n }));\r\n promise.isPromiseBasedObservable = true;\r\n promise.case = caseImpl;\r\n var oldData = oldPromise && (oldPromise.state === FULFILLED || oldPromise.state === PENDING)\r\n ? oldPromise.value\r\n : undefined;\r\n extendObservable(promise, {\r\n value: oldData,\r\n state: PENDING,\r\n }, {}, { deep: false });\r\n return promise;\r\n}\r\n(function (fromPromise) {\r\n fromPromise.reject = action(\"fromPromise.reject\", function (reason) {\r\n var p = fromPromise(Promise.reject(reason));\r\n p.state = REJECTED;\r\n p.value = reason;\r\n return p;\r\n });\r\n function resolveBase(value) {\r\n if (value === void 0) { value = undefined; }\r\n var p = fromPromise(Promise.resolve(value));\r\n p.state = FULFILLED;\r\n p.value = value;\r\n return p;\r\n }\r\n fromPromise.resolve = action(\"fromPromise.resolve\", resolveBase);\r\n})(fromPromise || (fromPromise = {}));\r\n/**\r\n * Returns true if the provided value is a promise-based observable.\r\n * @param value any\r\n * @returns {boolean}\r\n */\r\nfunction isPromiseBasedObservable(value) {\r\n return value && value.isPromiseBasedObservable === true;\r\n}\n\nvar __spreadArrays = (undefined && undefined.__spreadArrays) || function () {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n/**\r\n * Moves an item from one position to another, checking that the indexes given are within bounds.\r\n *\r\n * @example\r\n * const source = observable([1, 2, 3])\r\n * moveItem(source, 0, 1)\r\n * console.log(source.map(x => x)) // [2, 1, 3]\r\n *\r\n * @export\r\n * @param {ObservableArray} target\r\n * @param {number} fromIndex\r\n * @param {number} toIndex\r\n * @returns {ObservableArray}\r\n */\r\nfunction moveItem(target, fromIndex, toIndex) {\r\n checkIndex(target, fromIndex);\r\n checkIndex(target, toIndex);\r\n if (fromIndex === toIndex) {\r\n return;\r\n }\r\n var oldItems = target.slice();\r\n var newItems;\r\n if (fromIndex < toIndex) {\r\n newItems = __spreadArrays(oldItems.slice(0, fromIndex), oldItems.slice(fromIndex + 1, toIndex + 1), [\r\n oldItems[fromIndex]\r\n ], oldItems.slice(toIndex + 1));\r\n }\r\n else {\r\n // toIndex < fromIndex\r\n newItems = __spreadArrays(oldItems.slice(0, toIndex), [\r\n oldItems[fromIndex]\r\n ], oldItems.slice(toIndex, fromIndex), oldItems.slice(fromIndex + 1));\r\n }\r\n target.replace(newItems);\r\n return target;\r\n}\r\n/**\r\n * Checks whether the specified index is within bounds. Throws if not.\r\n *\r\n * @private\r\n * @param {ObservableArray} target\r\n * @param {number }index\r\n */\r\nfunction checkIndex(target, index) {\r\n if (index < 0) {\r\n throw new Error(\"[mobx.array] Index out of bounds: \" + index + \" is negative\");\r\n }\r\n var length = target.length;\r\n if (index >= length) {\r\n throw new Error(\"[mobx.array] Index out of bounds: \" + index + \" is not smaller than \" + length);\r\n }\r\n}\n\n/**\r\n * `lazyObservable` creates an observable around a `fetch` method that will not be invoked\r\n * until the observable is needed the first time.\r\n * The fetch method receives a `sink` callback which can be used to replace the\r\n * current value of the lazyObservable. It is allowed to call `sink` multiple times\r\n * to keep the lazyObservable up to date with some external resource.\r\n *\r\n * Note that it is the `current()` call itself which is being tracked by MobX,\r\n * so make sure that you don't dereference to early.\r\n *\r\n * @example\r\n * const userProfile = lazyObservable(\r\n * sink => fetch(\"/myprofile\").then(profile => sink(profile))\r\n * )\r\n *\r\n * // use the userProfile in a React component:\r\n * const Profile = observer(({ userProfile }) =>\r\n * userProfile.current() === undefined\r\n * ?
Loading user profile...
\r\n * :
{userProfile.current().displayName}
\r\n * )\r\n *\r\n * // triggers refresh the userProfile\r\n * userProfile.refresh()\r\n *\r\n * @param {(sink: (newValue: T) => void) => void} fetch method that will be called the first time the value of this observable is accessed. The provided sink can be used to produce a new value, synchronously or asynchronously\r\n * @param {T} [initialValue=undefined] optional initialValue that will be returned from `current` as long as the `sink` has not been called at least once\r\n * @returns {{\r\n * current(): T,\r\n * refresh(): T,\r\n * reset(): T\r\n * pending: boolean\r\n * }}\r\n */\r\nfunction lazyObservable(fetch, initialValue) {\r\n if (initialValue === void 0) { initialValue = undefined; }\r\n var started = false;\r\n var value = observable.box(initialValue, { deep: false });\r\n var pending = observable.box(false);\r\n var currentFnc = function () {\r\n if (!started) {\r\n started = true;\r\n _allowStateChanges(true, function () {\r\n pending.set(true);\r\n });\r\n fetch(function (newValue) {\r\n _allowStateChanges(true, function () {\r\n value.set(newValue);\r\n pending.set(false);\r\n });\r\n });\r\n }\r\n return value.get();\r\n };\r\n var resetFnc = action(\"lazyObservable-reset\", function () {\r\n started = false;\r\n value.set(initialValue);\r\n return value.get();\r\n });\r\n return {\r\n current: currentFnc,\r\n refresh: function () {\r\n if (started) {\r\n started = false;\r\n return currentFnc();\r\n }\r\n else {\r\n return value.get();\r\n }\r\n },\r\n reset: function () {\r\n return resetFnc();\r\n },\r\n get pending() {\r\n return pending.get();\r\n },\r\n };\r\n}\n\n/**\r\n * `fromResource` creates an observable whose current state can be inspected using `.current()`,\r\n * and which can be kept in sync with some external datasource that can be subscribed to.\r\n *\r\n * The created observable will only subscribe to the datasource if it is in use somewhere,\r\n * (un)subscribing when needed. To enable `fromResource` to do that two callbacks need to be provided,\r\n * one to subscribe, and one to unsubscribe. The subscribe callback itself will receive a `sink` callback, which can be used\r\n * to update the current state of the observable, allowing observes to react.\r\n *\r\n * Whatever is passed to `sink` will be returned by `current()`. The values passed to the sink will not be converted to\r\n * observables automatically, but feel free to do so.\r\n * It is the `current()` call itself which is being tracked,\r\n * so make sure that you don't dereference to early.\r\n *\r\n * For inspiration, an example integration with the apollo-client on [github](https://github.com/apollostack/apollo-client/issues/503#issuecomment-241101379),\r\n * or the [implementation](https://github.com/mobxjs/mobx-utils/blob/1d17cf7f7f5200937f68cc0b5e7ec7f3f71dccba/src/now.ts#L43-L57) of `mobxUtils.now`\r\n *\r\n * The following example code creates an observable that connects to a `dbUserRecord`,\r\n * which comes from an imaginary database and notifies when it has changed.\r\n *\r\n * @example\r\n * function createObservableUser(dbUserRecord) {\r\n * let currentSubscription;\r\n * return fromResource(\r\n * (sink) => {\r\n * // sink the current state\r\n * sink(dbUserRecord.fields)\r\n * // subscribe to the record, invoke the sink callback whenever new data arrives\r\n * currentSubscription = dbUserRecord.onUpdated(() => {\r\n * sink(dbUserRecord.fields)\r\n * })\r\n * },\r\n * () => {\r\n * // the user observable is not in use at the moment, unsubscribe (for now)\r\n * dbUserRecord.unsubscribe(currentSubscription)\r\n * }\r\n * )\r\n * }\r\n *\r\n * // usage:\r\n * const myUserObservable = createObservableUser(myDatabaseConnector.query(\"name = 'Michel'\"))\r\n *\r\n * // use the observable in autorun\r\n * autorun(() => {\r\n * // printed everytime the database updates its records\r\n * console.log(myUserObservable.current().displayName)\r\n * })\r\n *\r\n * // ... or a component\r\n * const userComponent = observer(({ user }) =>\r\n *
{user.current().displayName}
\r\n * )\r\n *\r\n * @export\r\n * @template T\r\n * @param {(sink: (newValue: T) => void) => void} subscriber\r\n * @param {IDisposer} [unsubscriber=NOOP]\r\n * @param {T} [initialValue=undefined] the data that will be returned by `get()` until the `sink` has emitted its first data\r\n * @returns {{\r\n * current(): T;\r\n * dispose(): void;\r\n * isAlive(): boolean;\r\n * }}\r\n */\r\nfunction fromResource(subscriber, unsubscriber, initialValue) {\r\n if (unsubscriber === void 0) { unsubscriber = NOOP; }\r\n if (initialValue === void 0) { initialValue = undefined; }\r\n var isActive = false;\r\n var isDisposed = false;\r\n var value = initialValue;\r\n var suspender = function () {\r\n if (isActive) {\r\n isActive = false;\r\n unsubscriber();\r\n }\r\n };\r\n var atom = createAtom(\"ResourceBasedObservable\", function () {\r\n invariant(!isActive && !isDisposed);\r\n isActive = true;\r\n subscriber(function (newValue) {\r\n _allowStateChanges(true, function () {\r\n value = newValue;\r\n atom.reportChanged();\r\n });\r\n });\r\n }, suspender);\r\n return {\r\n current: function () {\r\n invariant(!isDisposed, \"subscribingObservable has already been disposed\");\r\n var isBeingTracked = atom.reportObserved();\r\n if (!isBeingTracked && !isActive)\r\n console.warn(\"Called `get` of a subscribingObservable outside a reaction. Current value will be returned but no new subscription has started\");\r\n return value;\r\n },\r\n dispose: function () {\r\n isDisposed = true;\r\n suspender();\r\n },\r\n isAlive: function () { return isActive; },\r\n };\r\n}\n\nvar __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n};\r\nfunction observableSymbol() {\r\n return (typeof Symbol === \"function\" && Symbol.observable) || \"@@observable\";\r\n}\r\n/**\r\n * Converts an expression to an observable stream (a.k.a. TC 39 Observable / RxJS observable).\r\n * The provided expression is tracked by mobx as long as there are subscribers, automatically\r\n * emitting when new values become available. The expressions respect (trans)actions.\r\n *\r\n * @example\r\n *\r\n * const user = observable({\r\n * firstName: \"C.S\",\r\n * lastName: \"Lewis\"\r\n * })\r\n *\r\n * Rx.Observable\r\n * .from(mobxUtils.toStream(() => user.firstname + user.lastName))\r\n * .scan(nameChanges => nameChanges + 1, 0)\r\n * .subscribe(nameChanges => console.log(\"Changed name \", nameChanges, \"times\"))\r\n *\r\n * @export\r\n * @template T\r\n * @param {() => T} expression\r\n * @param {boolean} fireImmediately (by default false)\r\n * @returns {IObservableStream}\r\n */\r\nfunction toStream(expression, fireImmediately) {\r\n var _a;\r\n if (fireImmediately === void 0) { fireImmediately = false; }\r\n var computedValue = computed(expression);\r\n return _a = {\r\n subscribe: function (observer) {\r\n if (\"function\" === typeof observer) {\r\n return {\r\n unsubscribe: observe(computedValue, function (_a) {\r\n var newValue = _a.newValue;\r\n return observer(newValue);\r\n }, fireImmediately),\r\n };\r\n }\r\n if (observer && \"object\" === typeof observer && observer.next) {\r\n return {\r\n unsubscribe: observe(computedValue, function (_a) {\r\n var newValue = _a.newValue;\r\n return observer.next(newValue);\r\n }, fireImmediately),\r\n };\r\n }\r\n return {\r\n unsubscribe: function () { },\r\n };\r\n }\r\n },\r\n _a[observableSymbol()] = function () {\r\n return this;\r\n },\r\n _a;\r\n}\r\nvar StreamListener = /** @class */ (function () {\r\n function StreamListener(observable, initialValue) {\r\n var _this = this;\r\n Object.defineProperty(this, \"current\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: void 0\r\n });\r\n Object.defineProperty(this, \"subscription\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: void 0\r\n });\r\n makeObservable(this);\r\n runInAction(function () {\r\n _this.current = initialValue;\r\n _this.subscription = observable.subscribe(_this);\r\n });\r\n }\r\n Object.defineProperty(StreamListener.prototype, \"dispose\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function () {\r\n if (this.subscription) {\r\n this.subscription.unsubscribe();\r\n }\r\n }\r\n });\r\n Object.defineProperty(StreamListener.prototype, \"next\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function (value) {\r\n this.current = value;\r\n }\r\n });\r\n Object.defineProperty(StreamListener.prototype, \"complete\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function () {\r\n this.dispose();\r\n }\r\n });\r\n Object.defineProperty(StreamListener.prototype, \"error\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function (value) {\r\n this.current = value;\r\n this.dispose();\r\n }\r\n });\r\n __decorate([\r\n observable.ref\r\n ], StreamListener.prototype, \"current\", void 0);\r\n __decorate([\r\n action.bound\r\n ], StreamListener.prototype, \"next\", null);\r\n __decorate([\r\n action.bound\r\n ], StreamListener.prototype, \"complete\", null);\r\n __decorate([\r\n action.bound\r\n ], StreamListener.prototype, \"error\", null);\r\n return StreamListener;\r\n}());\r\nfunction fromStream(observable, initialValue) {\r\n if (initialValue === void 0) { initialValue = undefined; }\r\n return new StreamListener(observable, initialValue);\r\n}\n\nvar __assign = (undefined && undefined.__assign) || function () {\r\n __assign = Object.assign || function(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))\r\n t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\nvar __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n};\r\nvar RESERVED_NAMES = [\"model\", \"reset\", \"submit\", \"isDirty\", \"isPropertyDirty\", \"resetProperty\"];\r\nvar ViewModel = /** @class */ (function () {\r\n function ViewModel(model) {\r\n var _this = this;\r\n Object.defineProperty(this, \"model\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: model\r\n });\r\n Object.defineProperty(this, \"localValues\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: observable.map({})\r\n });\r\n Object.defineProperty(this, \"localComputedValues\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: observable.map({})\r\n });\r\n Object.defineProperty(this, \"isPropertyDirty\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: function (key) {\r\n return _this.localValues.has(key);\r\n }\r\n });\r\n makeObservable(this);\r\n invariant(isObservableObject(model), \"createViewModel expects an observable object\");\r\n var ownMethodsAndProperties = getAllMethodsAndProperties(this);\r\n // use this helper as Object.getOwnPropertyNames doesn't return getters\r\n getAllMethodsAndProperties(model).forEach(function (key) {\r\n var _a;\r\n if (ownMethodsAndProperties.includes(key)) {\r\n return;\r\n }\r\n if (key === $mobx || key === \"__mobxDidRunLazyInitializers\") {\r\n return;\r\n }\r\n invariant(RESERVED_NAMES.indexOf(key) === -1, \"The propertyname \" + key + \" is reserved and cannot be used with viewModels\");\r\n if (isComputedProp(model, key)) {\r\n var computedBox = _getAdministration(model, key); // Fixme: there is no clear api to get the derivation\r\n var get = computedBox.derivation.bind(_this);\r\n var set = (_a = computedBox.setter_) === null || _a === void 0 ? void 0 : _a.bind(_this);\r\n _this.localComputedValues.set(key, computed(get, { set: set }));\r\n }\r\n var descriptor = Object.getOwnPropertyDescriptor(model, key);\r\n var additionalDescriptor = descriptor ? { enumerable: descriptor.enumerable } : {};\r\n Object.defineProperty(_this, key, __assign(__assign({}, additionalDescriptor), { configurable: true, get: function () {\r\n if (isComputedProp(model, key))\r\n return _this.localComputedValues.get(key).get();\r\n if (_this.isPropertyDirty(key))\r\n return _this.localValues.get(key);\r\n else\r\n return _this.model[key];\r\n }, set: action(function (value) {\r\n if (isComputedProp(model, key)) {\r\n _this.localComputedValues.get(key).set(value);\r\n }\r\n else if (value !== _this.model[key]) {\r\n _this.localValues.set(key, value);\r\n }\r\n else {\r\n _this.localValues.delete(key);\r\n }\r\n }) }));\r\n });\r\n }\r\n Object.defineProperty(ViewModel.prototype, \"isDirty\", {\r\n get: function () {\r\n return this.localValues.size > 0;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n Object.defineProperty(ViewModel.prototype, \"changedValues\", {\r\n get: function () {\r\n return new Map(this.localValues);\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n Object.defineProperty(ViewModel.prototype, \"submit\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function () {\r\n var _this = this;\r\n keys(this.localValues).forEach(function (key) {\r\n var source = _this.localValues.get(key);\r\n var destination = _this.model[key];\r\n if (isObservableArray(destination)) {\r\n destination.replace(source);\r\n }\r\n else if (isObservableMap(destination)) {\r\n destination.clear();\r\n destination.merge(source);\r\n }\r\n else if (!isComputed(source)) {\r\n _this.model[key] = source;\r\n }\r\n });\r\n this.localValues.clear();\r\n }\r\n });\r\n Object.defineProperty(ViewModel.prototype, \"reset\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function () {\r\n this.localValues.clear();\r\n }\r\n });\r\n Object.defineProperty(ViewModel.prototype, \"resetProperty\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function (key) {\r\n this.localValues.delete(key);\r\n }\r\n });\r\n __decorate$1([\r\n computed\r\n ], ViewModel.prototype, \"isDirty\", null);\r\n __decorate$1([\r\n computed\r\n ], ViewModel.prototype, \"changedValues\", null);\r\n __decorate$1([\r\n action.bound\r\n ], ViewModel.prototype, \"submit\", null);\r\n __decorate$1([\r\n action.bound\r\n ], ViewModel.prototype, \"reset\", null);\r\n __decorate$1([\r\n action.bound\r\n ], ViewModel.prototype, \"resetProperty\", null);\r\n return ViewModel;\r\n}());\r\n/**\r\n * `createViewModel` takes an object with observable properties (model)\r\n * and wraps a viewmodel around it. The viewmodel proxies all enumerable properties of the original model with the following behavior:\r\n * - as long as no new value has been assigned to the viewmodel property, the original property will be returned.\r\n * - any future change in the model will be visible in the viewmodel as well unless the viewmodel property was dirty at the time of the attempted change.\r\n * - once a new value has been assigned to a property of the viewmodel, that value will be returned during a read of that property in the future. However, the original model remain untouched until `submit()` is called.\r\n *\r\n * The viewmodel exposes the following additional methods, besides all the enumerable properties of the model:\r\n * - `submit()`: copies all the values of the viewmodel to the model and resets the state\r\n * - `reset()`: resets the state of the viewmodel, abandoning all local modifications\r\n * - `resetProperty(propName)`: resets the specified property of the viewmodel\r\n * - `isDirty`: observable property indicating if the viewModel contains any modifications\r\n * - `isPropertyDirty(propName)`: returns true if the specified property is dirty\r\n * - `changedValues`: returns a key / value map with the properties that have been changed in the model so far\r\n * - `model`: The original model object for which this viewModel was created\r\n *\r\n * You may use observable arrays, maps and objects with `createViewModel` but keep in mind to assign fresh instances of those to the viewmodel's properties, otherwise you would end up modifying the properties of the original model.\r\n * Note that if you read a non-dirty property, viewmodel only proxies the read to the model. You therefore need to assign a fresh instance not only the first time you make the assignment but also after calling `reset()` or `submit()`.\r\n *\r\n * @example\r\n * class Todo {\r\n * \\@observable title = \"Test\"\r\n * }\r\n *\r\n * const model = new Todo()\r\n * const viewModel = createViewModel(model);\r\n *\r\n * autorun(() => console.log(viewModel.model.title, \",\", viewModel.title))\r\n * // prints \"Test, Test\"\r\n * model.title = \"Get coffee\"\r\n * // prints \"Get coffee, Get coffee\", viewModel just proxies to model\r\n * viewModel.title = \"Get tea\"\r\n * // prints \"Get coffee, Get tea\", viewModel's title is now dirty, and the local value will be printed\r\n * viewModel.submit()\r\n * // prints \"Get tea, Get tea\", changes submitted from the viewModel to the model, viewModel is proxying again\r\n * viewModel.title = \"Get cookie\"\r\n * // prints \"Get tea, Get cookie\" // viewModel has diverged again\r\n * viewModel.reset()\r\n * // prints \"Get tea, Get tea\", changes of the viewModel have been abandoned\r\n *\r\n * @param {T} model\r\n * @returns {(T & IViewModel)}\r\n * ```\r\n */\r\nfunction createViewModel(model) {\r\n return new ViewModel(model);\r\n}\n\n/**\r\n * MobX normally suspends any computed value that is not in use by any reaction,\r\n * and lazily re-evaluates the expression if needed outside a reaction while not in use.\r\n * `keepAlive` marks a computed value as always in use, meaning that it will always fresh, but never disposed automatically.\r\n *\r\n * @example\r\n * const obj = observable({\r\n * number: 3,\r\n * doubler: function() { return this.number * 2 }\r\n * })\r\n * const stop = keepAlive(obj, \"doubler\")\r\n *\r\n * @param {Object} target an object that has a computed property, created by `@computed` or `extendObservable`\r\n * @param {string} property the name of the property to keep alive\r\n * @returns {IDisposer} stops this keep alive so that the computed value goes back to normal behavior\r\n */\r\n/**\r\n * @example\r\n * const number = observable(3)\r\n * const doubler = computed(() => number.get() * 2)\r\n * const stop = keepAlive(doubler)\r\n * // doubler will now stay in sync reactively even when there are no further observers\r\n * stop()\r\n * // normal behavior, doubler results will be recomputed if not observed but needed, but lazily\r\n *\r\n * @param {IComputedValue} computedValue created using the `computed` function\r\n * @returns {IDisposer} stops this keep alive so that the computed value goes back to normal behavior\r\n */\r\nfunction keepAlive(_1, _2) {\r\n var computed = getAtom(_1, _2);\r\n if (!computed)\r\n throw new Error(\"No computed provided, please provide an object created with `computed(() => expr)` or an object + property name\");\r\n return observe(computed, function () { });\r\n}\n\n/**\r\n * `queueProcessor` takes an observable array, observes it and calls `processor`\r\n * once for each item added to the observable array, optionally debouncing the action\r\n *\r\n * @example\r\n * const pendingNotifications = observable([])\r\n * const stop = queueProcessor(pendingNotifications, msg => {\r\n * // show Desktop notification\r\n * new Notification(msg);\r\n * })\r\n *\r\n * // usage:\r\n * pendingNotifications.push(\"test!\")\r\n *\r\n * @param {T[]} observableArray observable array instance to track\r\n * @param {(item: T) => void} processor action to call per item\r\n * @param {number} [debounce=0] optional debounce time in ms. With debounce 0 the processor will run synchronously\r\n * @returns {IDisposer} stops the processor\r\n */\r\nfunction queueProcessor(observableArray, processor, debounce) {\r\n if (debounce === void 0) { debounce = 0; }\r\n if (!isObservableArray(observableArray))\r\n throw new Error(\"Expected observable array as first argument\");\r\n if (!isAction(processor))\r\n processor = action(\"queueProcessor\", processor);\r\n var runner = function () {\r\n // construct a final set\r\n var items = observableArray.slice(0);\r\n // clear the queue for next iteration\r\n runInAction(function () { return observableArray.splice(0); });\r\n // fire processor\r\n items.forEach(processor);\r\n };\r\n if (debounce > 0)\r\n return autorun(runner, { delay: debounce });\r\n else\r\n return autorun(runner);\r\n}\n\n/**\r\n * `chunkProcessor` takes an observable array, observes it and calls `processor`\r\n * once for a chunk of items added to the observable array, optionally deboucing the action.\r\n * The maximum chunk size can be limited by number.\r\n * This allows both, splitting larger into smaller chunks or (when debounced) combining smaller\r\n * chunks and/or single items into reasonable chunks of work.\r\n *\r\n * @example\r\n * const trackedActions = observable([])\r\n * const stop = chunkProcessor(trackedActions, chunkOfMax10Items => {\r\n * sendTrackedActionsToServer(chunkOfMax10Items);\r\n * }, 100, 10)\r\n *\r\n * // usage:\r\n * trackedActions.push(\"scrolled\")\r\n * trackedActions.push(\"hoveredButton\")\r\n * // when both pushes happen within 100ms, there will be only one call to server\r\n *\r\n * @param {T[]} observableArray observable array instance to track\r\n * @param {(item: T[]) => void} processor action to call per item\r\n * @param {number} [debounce=0] optional debounce time in ms. With debounce 0 the processor will run synchronously\r\n * @param {number} [maxChunkSize=0] optionally do not call on full array but smaller chunks. With 0 it will process the full array.\r\n * @returns {IDisposer} stops the processor\r\n */\r\nfunction chunkProcessor(observableArray, processor, debounce, maxChunkSize) {\r\n if (debounce === void 0) { debounce = 0; }\r\n if (maxChunkSize === void 0) { maxChunkSize = 0; }\r\n if (!isObservableArray(observableArray))\r\n throw new Error(\"Expected observable array as first argument\");\r\n if (!isAction(processor))\r\n processor = action(\"chunkProcessor\", processor);\r\n var runner = function () {\r\n var _loop_1 = function () {\r\n var chunkSize = maxChunkSize === 0\r\n ? observableArray.length\r\n : Math.min(observableArray.length, maxChunkSize);\r\n // construct a final set\r\n var items = observableArray.slice(0, chunkSize);\r\n // clear the slice for next iteration\r\n runInAction(function () { return observableArray.splice(0, chunkSize); });\r\n // fire processor\r\n processor(items);\r\n };\r\n while (observableArray.length > 0) {\r\n _loop_1();\r\n }\r\n };\r\n if (debounce > 0)\r\n return autorun(runner, { delay: debounce });\r\n else\r\n return autorun(runner);\r\n}\n\nvar tickers = {};\r\n/**\r\n * Disposes of all the internal Observables created by invocations of `now()`.\r\n *\r\n * The use case for this is to ensure that unit tests can run independent of each other.\r\n * You should not call this in regular application code.\r\n *\r\n * @example\r\n * afterEach(() => {\r\n * utils.resetNowInternalState()\r\n * })\r\n */\r\nfunction resetNowInternalState() {\r\n for (var _i = 0, _a = Object.getOwnPropertyNames(tickers); _i < _a.length; _i++) {\r\n var key = _a[_i];\r\n tickers[key].dispose();\r\n delete tickers[key];\r\n }\r\n}\r\n/**\r\n * Returns the current date time as epoch number.\r\n * The date time is read from an observable which is updated automatically after the given interval.\r\n * So basically it treats time as an observable.\r\n *\r\n * The function takes an interval as parameter, which indicates how often `now()` will return a new value.\r\n * If no interval is given, it will update each second. If \"frame\" is specified, it will update each time a\r\n * `requestAnimationFrame` is available.\r\n *\r\n * Multiple clocks with the same interval will automatically be synchronized.\r\n *\r\n * Countdown example: https://jsfiddle.net/mweststrate/na0qdmkw/\r\n *\r\n * @example\r\n *\r\n * const start = Date.now()\r\n *\r\n * autorun(() => {\r\n * console.log(\"Seconds elapsed: \", (mobxUtils.now() - start) / 1000)\r\n * })\r\n *\r\n *\r\n * @export\r\n * @param {(number | \"frame\")} [interval=1000] interval in milliseconds about how often the interval should update\r\n * @returns\r\n */\r\nfunction now(interval) {\r\n if (interval === void 0) { interval = 1000; }\r\n if (!_isComputingDerivation()) {\r\n // See #40\r\n return Date.now();\r\n }\r\n if (!tickers[interval]) {\r\n if (typeof interval === \"number\")\r\n tickers[interval] = createIntervalTicker(interval);\r\n else\r\n tickers[interval] = createAnimationFrameTicker();\r\n }\r\n return tickers[interval].current();\r\n}\r\nfunction createIntervalTicker(interval) {\r\n var subscriptionHandle;\r\n return fromResource(function (sink) {\r\n sink(Date.now());\r\n subscriptionHandle = setInterval(function () { return sink(Date.now()); }, interval);\r\n }, function () {\r\n clearInterval(subscriptionHandle);\r\n }, Date.now());\r\n}\r\nfunction createAnimationFrameTicker() {\r\n var frameBasedTicker = fromResource(function (sink) {\r\n sink(Date.now());\r\n function scheduleTick() {\r\n window.requestAnimationFrame(function () {\r\n sink(Date.now());\r\n if (frameBasedTicker.isAlive())\r\n scheduleTick();\r\n });\r\n }\r\n scheduleTick();\r\n }, function () { }, Date.now());\r\n return frameBasedTicker;\r\n}\n\n/**\r\n *`expr` can be used to create temporary computed values inside computed values.\r\n * Nesting computed values is useful to create cheap computations in order to prevent expensive computations from needing to run.\r\n * In the following example the expression prevents that a component is rerender _each time_ the selection changes;\r\n * instead it will only rerenders when the current todo is (de)selected.\r\n *\r\n * `expr(func)` is an alias for `computed(func).get()`.\r\n * Please note that the function given to `expr` is evaluated _twice_ in the scenario that the overall expression value changes.\r\n * It is evaluated the first time when any observables it depends on change.\r\n * It is evaluated a second time when a change in its value triggers the outer computed or reaction to evaluate, which recreates and reevaluates the expression.\r\n *\r\n * In the following example, the expression prevents the `TodoView` component from being re-rendered if the selection changes elsewhere.\r\n * Instead, the component will only re-render when the relevant todo is (de)selected, which happens much less frequently.\r\n *\r\n * @example\r\n * const Todo = observer((props) => {\r\n * const todo = props.todo\r\n * const isSelected = mobxUtils.expr(() => props.viewState.selection === todo)\r\n * const TodoView = observer(({ todo, editorState }) => {\r\n * const isSelected = mobxUtils.expr(() => editorState.selection === todo)\r\n * return
{todo.title}
\r\n * })\r\n */\r\nfunction expr(expr) {\r\n if (!_isComputingDerivation())\r\n console.warn(\"'expr' should only be used inside other reactive functions.\");\r\n // optimization: would be more efficient if the expr itself wouldn't be evaluated first on the next change, but just a 'changed' signal would be fired\r\n return computed(expr).get();\r\n}\n\nvar __assign$1 = (undefined && undefined.__assign) || function () {\r\n __assign$1 = Object.assign || function(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))\r\n t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign$1.apply(this, arguments);\r\n};\r\nvar memoizationId = 0;\r\n/**\r\n * Creates a function that maps an object to a view.\r\n * The mapping is memoized.\r\n *\r\n * See the [transformer](#createtransformer-in-detail) section for more details.\r\n *\r\n * @param transformer\r\n * @param onCleanup\r\n */\r\nfunction createTransformer(transformer, arg2) {\r\n invariant(typeof transformer === \"function\" && transformer.length < 2, \"createTransformer expects a function that accepts one argument\");\r\n // Memoizes: object id -> reactive view that applies transformer to the object\r\n var views = {};\r\n var onCleanup = undefined;\r\n var keepAlive = false;\r\n var debugNameGenerator = undefined;\r\n if (typeof arg2 === \"object\") {\r\n onCleanup = arg2.onCleanup;\r\n keepAlive = arg2.keepAlive !== undefined ? arg2.keepAlive : false;\r\n debugNameGenerator = arg2.debugNameGenerator;\r\n }\r\n else if (typeof arg2 === \"function\") {\r\n onCleanup = arg2;\r\n }\r\n function createView(sourceIdentifier, sourceObject) {\r\n var latestValue;\r\n var computedValueOptions = {};\r\n if (typeof arg2 === \"object\") {\r\n onCleanup = arg2.onCleanup;\r\n debugNameGenerator = arg2.debugNameGenerator;\r\n computedValueOptions = arg2;\r\n }\r\n else if (typeof arg2 === \"function\") {\r\n onCleanup = arg2;\r\n }\r\n else {\r\n onCleanup = undefined;\r\n debugNameGenerator = undefined;\r\n }\r\n var prettifiedName = debugNameGenerator\r\n ? debugNameGenerator(sourceObject)\r\n : \"Transformer-\" + transformer.name + \"-\" + sourceIdentifier;\r\n var expr = computed(function () {\r\n return (latestValue = transformer(sourceObject));\r\n }, __assign$1(__assign$1({}, computedValueOptions), { name: prettifiedName }));\r\n if (!keepAlive) {\r\n var disposer_1 = onBecomeUnobserved(expr, function () {\r\n delete views[sourceIdentifier];\r\n disposer_1();\r\n if (onCleanup)\r\n onCleanup(latestValue, sourceObject);\r\n });\r\n }\r\n return expr;\r\n }\r\n var memoWarned = false;\r\n return function (object) {\r\n var identifier = getMemoizationId(object);\r\n var reactiveView = views[identifier];\r\n if (reactiveView)\r\n return reactiveView.get();\r\n if (!keepAlive && !_isComputingDerivation()) {\r\n if (!memoWarned) {\r\n console.warn(\"invoking a transformer from outside a reactive context won't memorized \" +\r\n \"and is cleaned up immediately, unless keepAlive is set\");\r\n memoWarned = true;\r\n }\r\n var value = transformer(object);\r\n if (onCleanup)\r\n onCleanup(value, object);\r\n return value;\r\n }\r\n // Not in cache; create a reactive view\r\n reactiveView = views[identifier] = createView(identifier, object);\r\n return reactiveView.get();\r\n };\r\n}\r\nfunction getMemoizationId(object) {\r\n var objectType = typeof object;\r\n if (objectType === \"string\")\r\n return \"string:\" + object;\r\n if (objectType === \"number\")\r\n return \"number:\" + object;\r\n if (object === null || (objectType !== \"object\" && objectType !== \"function\"))\r\n throw new Error(\"[mobx-utils] transform expected an object, function, string or number, got: \" + String(object));\r\n var tid = object.$transformId;\r\n if (tid === undefined) {\r\n tid = \"memoizationId:\" + ++memoizationId;\r\n addHiddenProp(object, \"$transformId\", tid);\r\n }\r\n return tid;\r\n}\n\nfunction buildPath(entry) {\r\n if (!entry)\r\n return \"ROOT\";\r\n var res = [];\r\n while (entry.parent) {\r\n res.push(entry.path);\r\n entry = entry.parent;\r\n }\r\n return res.reverse().join(\"/\");\r\n}\r\nfunction isRecursivelyObservable(thing) {\r\n return isObservableObject(thing) || isObservableArray(thing) || isObservableMap(thing);\r\n}\r\n/**\r\n * Given an object, deeply observes the given object.\r\n * It is like `observe` from mobx, but applied recursively, including all future children.\r\n *\r\n * Note that the given object cannot ever contain cycles and should be a tree.\r\n *\r\n * As benefit: path and root will be provided in the callback, so the signature of the listener is\r\n * (change, path, root) => void\r\n *\r\n * The returned disposer can be invoked to clean up the listener\r\n *\r\n * deepObserve cannot be used on computed values.\r\n *\r\n * @example\r\n * const disposer = deepObserve(target, (change, path) => {\r\n * console.dir(change)\r\n * })\r\n */\r\nfunction deepObserve(target, listener) {\r\n var entrySet = new WeakMap();\r\n function genericListener(change) {\r\n var entry = entrySet.get(change.object);\r\n processChange(change, entry);\r\n listener(change, buildPath(entry), target);\r\n }\r\n function processChange(change, parent) {\r\n switch (change.type) {\r\n // Object changes\r\n case \"add\": // also for map\r\n observeRecursively(change.newValue, parent, change.name);\r\n break;\r\n case \"update\": // also for array and map\r\n unobserveRecursively(change.oldValue);\r\n observeRecursively(change.newValue, parent, change.name || \"\" + change.index);\r\n break;\r\n case \"remove\": // object\r\n case \"delete\": // map\r\n unobserveRecursively(change.oldValue);\r\n break;\r\n // Array changes\r\n case \"splice\":\r\n change.removed.map(unobserveRecursively);\r\n change.added.forEach(function (value, idx) {\r\n return observeRecursively(value, parent, \"\" + (change.index + idx));\r\n });\r\n // update paths\r\n for (var i = change.index + change.addedCount; i < change.object.length; i++) {\r\n if (isRecursivelyObservable(change.object[i])) {\r\n var entry = entrySet.get(change.object[i]);\r\n if (entry)\r\n entry.path = \"\" + i;\r\n }\r\n }\r\n break;\r\n }\r\n }\r\n function observeRecursively(thing, parent, path) {\r\n if (isRecursivelyObservable(thing)) {\r\n var entry = entrySet.get(thing);\r\n if (entry) {\r\n if (entry.parent !== parent || entry.path !== path)\r\n // MWE: this constraint is artificial, and this tool could be made to work with cycles,\r\n // but it increases administration complexity, has tricky edge cases and the meaning of 'path'\r\n // would become less clear. So doesn't seem to be needed for now\r\n throw new Error(\"The same observable object cannot appear twice in the same tree,\" +\r\n (\" trying to assign it to '\" + buildPath(parent) + \"/\" + path + \"',\") +\r\n (\" but it already exists at '\" + buildPath(entry.parent) + \"/\" + entry.path + \"'\"));\r\n }\r\n else {\r\n var entry_1 = {\r\n parent: parent,\r\n path: path,\r\n dispose: observe(thing, genericListener),\r\n };\r\n entrySet.set(thing, entry_1);\r\n entries(thing).forEach(function (_a) {\r\n var key = _a[0], value = _a[1];\r\n return observeRecursively(value, entry_1, key);\r\n });\r\n }\r\n }\r\n }\r\n function unobserveRecursively(thing) {\r\n if (isRecursivelyObservable(thing)) {\r\n var entry = entrySet.get(thing);\r\n if (!entry)\r\n return;\r\n entrySet.delete(thing);\r\n entry.dispose();\r\n values(thing).forEach(unobserveRecursively);\r\n }\r\n }\r\n observeRecursively(target, undefined, \"\");\r\n return function () {\r\n unobserveRecursively(target);\r\n };\r\n}\n\nvar __extends = (undefined && undefined.__extends) || (function () {\r\n var extendStatics = function (d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n };\r\n return function (d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n };\r\n})();\r\n/**\r\n * Reactively sorts a base observable array into multiple observable arrays based on the value of a\r\n * `groupBy: (item: T) => G` function.\r\n *\r\n * This observes the individual computed groupBy values and only updates the source and dest arrays\r\n * when there is an actual change, so this is far more efficient than, for example\r\n * `base.filter(i => groupBy(i) === 'we')`. Call #dispose() to stop tracking.\r\n *\r\n * No guarantees are made about the order of items in the grouped arrays.\r\n *\r\n * The resulting map of arrays is read-only. clear(), set(), delete() are not supported and\r\n * modifying the group arrays will lead to undefined behavior.\r\n *\r\n * NB: ObservableGroupMap relies on `Symbol`s. If you are targeting a platform which doesn't\r\n * support these natively, you will need to provide a polyfill.\r\n *\r\n * @param {array} base The array to sort into groups.\r\n * @param {function} groupBy The function used for grouping.\r\n * @param options Object with properties:\r\n * `name`: Debug name of this ObservableGroupMap.\r\n * `keyToName`: Function to create the debug names of the observable group arrays.\r\n *\r\n * @example\r\n * const slices = observable([\r\n * { day: \"mo\", hours: 12 },\r\n * { day: \"tu\", hours: 2 },\r\n * ])\r\n * const slicesByDay = new ObservableGroupMap(slices, (slice) => slice.day)\r\n * autorun(() => console.log(\r\n * slicesByDay.get(\"mo\")?.length ?? 0,\r\n * slicesByDay.get(\"we\"))) // outputs 1, undefined\r\n * slices[0].day = \"we\" // outputs 0, [{ day: \"we\", hours: 12 }]\r\n */\r\nvar ObservableGroupMap = /** @class */ (function (_super) {\r\n __extends(ObservableGroupMap, _super);\r\n function ObservableGroupMap(base, groupBy, _a) {\r\n var _b = _a === void 0 ? {} : _a, _c = _b.name, name = _c === void 0 ? \"ogm\" + ((Math.random() * 1000) | 0) : _c, _d = _b.keyToName, keyToName = _d === void 0 ? function (x) { return \"\" + x; } : _d;\r\n var _this = _super.call(this) || this;\r\n /**\r\n * Base observable array which is being sorted into groups.\r\n */\r\n Object.defineProperty(_this, \"_base\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: void 0\r\n });\r\n /**\r\n * The ObservableGroupMap needs to track some state per-item. This is the name/symbol of the\r\n * property used to attach the state.\r\n */\r\n Object.defineProperty(_this, \"_ogmInfoKey\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: void 0\r\n });\r\n /**\r\n * The function used to group the items.\r\n */\r\n Object.defineProperty(_this, \"_groupBy\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: void 0\r\n });\r\n /**\r\n * This function is used to generate the mobx debug names of the observable group arrays.\r\n */\r\n Object.defineProperty(_this, \"_keyToName\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: void 0\r\n });\r\n Object.defineProperty(_this, \"_disposeBaseObserver\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: void 0\r\n });\r\n _this._keyToName = keyToName;\r\n _this._groupBy = groupBy;\r\n _this._ogmInfoKey = Symbol(\"ogmInfo\" + name);\r\n _this._base = base;\r\n for (var i = 0; i < base.length; i++) {\r\n _this._addItem(base[i]);\r\n }\r\n _this._disposeBaseObserver = observe(_this._base, function (change) {\r\n if (\"splice\" === change.type) {\r\n transaction(function () {\r\n for (var _i = 0, _a = change.removed; _i < _a.length; _i++) {\r\n var removed = _a[_i];\r\n _this._removeItem(removed);\r\n }\r\n for (var _b = 0, _c = change.added; _b < _c.length; _b++) {\r\n var added = _c[_b];\r\n _this._addItem(added);\r\n }\r\n });\r\n }\r\n else if (\"update\" === change.type) {\r\n transaction(function () {\r\n _this._removeItem(change.oldValue);\r\n _this._addItem(change.newValue);\r\n });\r\n }\r\n else {\r\n throw new Error(\"illegal state\");\r\n }\r\n });\r\n return _this;\r\n }\r\n Object.defineProperty(ObservableGroupMap.prototype, \"clear\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function () {\r\n throw new Error(\"not supported\");\r\n }\r\n });\r\n Object.defineProperty(ObservableGroupMap.prototype, \"delete\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function (_key) {\r\n throw new Error(\"not supported\");\r\n }\r\n });\r\n Object.defineProperty(ObservableGroupMap.prototype, \"set\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function (_key, _value) {\r\n throw new Error(\"not supported\");\r\n }\r\n });\r\n /**\r\n * Disposes all observers created during construction and removes state added to base array\r\n * items.\r\n */\r\n Object.defineProperty(ObservableGroupMap.prototype, \"dispose\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function () {\r\n this._disposeBaseObserver();\r\n for (var i = 0; i < this._base.length; i++) {\r\n var item = this._base[i];\r\n var grouperItemInfo = item[this._ogmInfoKey];\r\n grouperItemInfo.reaction();\r\n delete item[this._ogmInfoKey];\r\n }\r\n }\r\n });\r\n Object.defineProperty(ObservableGroupMap.prototype, \"_getGroupArr\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function (key) {\r\n var result = _super.prototype.get.call(this, key);\r\n if (undefined === result) {\r\n result = observable([], { name: \"GroupArray[\" + this._keyToName(key) + \"]\", deep: false });\r\n _super.prototype.set.call(this, key, result);\r\n }\r\n return result;\r\n }\r\n });\r\n Object.defineProperty(ObservableGroupMap.prototype, \"_removeFromGroupArr\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function (key, itemIndex) {\r\n var arr = _super.prototype.get.call(this, key);\r\n if (1 === arr.length) {\r\n _super.prototype.delete.call(this, key);\r\n }\r\n else if (itemIndex === arr.length - 1) {\r\n // last position in array\r\n arr.length--;\r\n }\r\n else {\r\n arr[itemIndex] = arr[arr.length - 1];\r\n arr[itemIndex][this._ogmInfoKey].groupArrIndex = itemIndex;\r\n arr.length--;\r\n }\r\n }\r\n });\r\n Object.defineProperty(ObservableGroupMap.prototype, \"_addItem\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function (item) {\r\n var _this = this;\r\n var groupByValue = this._groupBy(item);\r\n var groupArr = this._getGroupArr(groupByValue);\r\n var value = {\r\n groupByValue: groupByValue,\r\n groupArrIndex: groupArr.length,\r\n reaction: reaction(function () { return _this._groupBy(item); }, function (newGroupByValue, _r) {\r\n var grouperItemInfo = item[_this._ogmInfoKey];\r\n _this._removeFromGroupArr(grouperItemInfo.groupByValue, grouperItemInfo.groupArrIndex);\r\n var newGroupArr = _this._getGroupArr(newGroupByValue);\r\n var newGroupArrIndex = newGroupArr.length;\r\n newGroupArr.push(item);\r\n grouperItemInfo.groupByValue = newGroupByValue;\r\n grouperItemInfo.groupArrIndex = newGroupArrIndex;\r\n }),\r\n };\r\n Object.defineProperty(item, this._ogmInfoKey, {\r\n configurable: true,\r\n enumerable: false,\r\n value: value,\r\n });\r\n groupArr.push(item);\r\n }\r\n });\r\n Object.defineProperty(ObservableGroupMap.prototype, \"_removeItem\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function (item) {\r\n var grouperItemInfo = item[this._ogmInfoKey];\r\n this._removeFromGroupArr(grouperItemInfo.groupByValue, grouperItemInfo.groupArrIndex);\r\n grouperItemInfo.reaction();\r\n delete item[this._ogmInfoKey];\r\n }\r\n });\r\n return ObservableGroupMap;\r\n}(ObservableMap));\n\n/**\r\n * @private\r\n */\r\nvar DeepMapEntry = /** @class */ (function () {\r\n function DeepMapEntry(base, args) {\r\n Object.defineProperty(this, \"base\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: base\r\n });\r\n Object.defineProperty(this, \"args\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: args\r\n });\r\n Object.defineProperty(this, \"root\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: void 0\r\n });\r\n Object.defineProperty(this, \"closest\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: void 0\r\n });\r\n Object.defineProperty(this, \"closestIdx\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: 0\r\n });\r\n Object.defineProperty(this, \"isDisposed\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: false\r\n });\r\n var current = (this.closest = this.root = base);\r\n var i = 0;\r\n for (; i < this.args.length - 1; i++) {\r\n current = current.get(args[i]);\r\n if (current)\r\n this.closest = current;\r\n else\r\n break;\r\n }\r\n this.closestIdx = i;\r\n }\r\n Object.defineProperty(DeepMapEntry.prototype, \"exists\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function () {\r\n this.assertNotDisposed();\r\n var l = this.args.length;\r\n return this.closestIdx >= l - 1 && this.closest.has(this.args[l - 1]);\r\n }\r\n });\r\n Object.defineProperty(DeepMapEntry.prototype, \"get\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function () {\r\n this.assertNotDisposed();\r\n if (!this.exists())\r\n throw new Error(\"Entry doesn't exist\");\r\n return this.closest.get(this.args[this.args.length - 1]);\r\n }\r\n });\r\n Object.defineProperty(DeepMapEntry.prototype, \"set\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function (value) {\r\n this.assertNotDisposed();\r\n var l = this.args.length;\r\n var current = this.closest;\r\n // create remaining maps\r\n for (var i = this.closestIdx; i < l - 1; i++) {\r\n var m = new Map();\r\n current.set(this.args[i], m);\r\n current = m;\r\n }\r\n this.closestIdx = l - 1;\r\n this.closest = current;\r\n current.set(this.args[l - 1], value);\r\n }\r\n });\r\n Object.defineProperty(DeepMapEntry.prototype, \"delete\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function () {\r\n this.assertNotDisposed();\r\n if (!this.exists())\r\n throw new Error(\"Entry doesn't exist\");\r\n var l = this.args.length;\r\n this.closest.delete(this.args[l - 1]);\r\n // clean up remaining maps if needed (reconstruct stack first)\r\n var c = this.root;\r\n var maps = [c];\r\n for (var i = 0; i < l - 1; i++) {\r\n c = c.get(this.args[i]);\r\n maps.push(c);\r\n }\r\n for (var i = maps.length - 1; i > 0; i--) {\r\n if (maps[i].size === 0)\r\n maps[i - 1].delete(this.args[i - 1]);\r\n }\r\n this.isDisposed = true;\r\n }\r\n });\r\n Object.defineProperty(DeepMapEntry.prototype, \"assertNotDisposed\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function () {\r\n // TODO: once this becomes annoying, we should introduce a reset method to re-run the constructor logic\r\n if (this.isDisposed)\r\n throw new Error(\"Concurrent modification exception\");\r\n }\r\n });\r\n return DeepMapEntry;\r\n}());\r\n/**\r\n * @private\r\n */\r\nvar DeepMap = /** @class */ (function () {\r\n function DeepMap() {\r\n Object.defineProperty(this, \"store\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: new Map()\r\n });\r\n Object.defineProperty(this, \"argsLength\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: -1\r\n });\r\n Object.defineProperty(this, \"last\", {\r\n enumerable: true,\r\n configurable: true,\r\n writable: true,\r\n value: void 0\r\n });\r\n }\r\n Object.defineProperty(DeepMap.prototype, \"entry\", {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function (args) {\r\n if (this.argsLength === -1)\r\n this.argsLength = args.length;\r\n else if (this.argsLength !== args.length)\r\n throw new Error(\"DeepMap should be used with functions with a consistent length, expected: \" + this.argsLength + \", got: \" + args.length);\r\n if (this.last)\r\n this.last.isDisposed = true;\r\n return (this.last = new DeepMapEntry(this.store, args));\r\n }\r\n });\r\n return DeepMap;\r\n}());\n\nvar __assign$2 = (undefined && undefined.__assign) || function () {\r\n __assign$2 = Object.assign || function(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))\r\n t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign$2.apply(this, arguments);\r\n};\r\nvar __spreadArrays$1 = (undefined && undefined.__spreadArrays) || function () {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n/**\r\n * computedFn takes a function with an arbitrary amount of arguments,\r\n * and memoizes the output of the function based on the arguments passed in.\r\n *\r\n * computedFn(fn) returns a function with the very same signature. There is no limit on the amount of arguments\r\n * that is accepted. However, the amount of arguments must be constant and default arguments are not supported.\r\n *\r\n * By default the output of a function call will only be memoized as long as the\r\n * output is being observed.\r\n *\r\n * The function passes into `computedFn` should be pure, not be an action and only be relying on\r\n * observables.\r\n *\r\n * Setting `keepAlive` to `true` will cause the output to be forcefully cached forever.\r\n * Note that this might introduce memory leaks!\r\n *\r\n * @example\r\n * const store = observable({\r\n a: 1,\r\n b: 2,\r\n c: 3,\r\n m: computedFn(function(x) {\r\n return this.a * this.b * x\r\n })\r\n })\r\n\r\n const d = autorun(() => {\r\n // store.m(3) will be cached as long as this autorun is running\r\n console.log(store.m(3) * store.c)\r\n })\r\n *\r\n * @param fn\r\n * @param keepAliveOrOptions\r\n */\r\nfunction computedFn(fn, keepAliveOrOptions) {\r\n if (keepAliveOrOptions === void 0) { keepAliveOrOptions = false; }\r\n if (isAction(fn))\r\n throw new Error(\"computedFn shouldn't be used on actions\");\r\n var memoWarned = false;\r\n var i = 0;\r\n var opts = typeof keepAliveOrOptions === \"boolean\"\r\n ? { keepAlive: keepAliveOrOptions }\r\n : keepAliveOrOptions;\r\n var d = new DeepMap();\r\n return function () {\r\n var _this = this;\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n var entry = d.entry(args);\r\n // cache hit, return\r\n if (entry.exists())\r\n return entry.get().get();\r\n // if function is invoked, and its a cache miss without reactive, there is no point in caching...\r\n if (!opts.keepAlive && !_isComputingDerivation()) {\r\n if (!memoWarned && _getGlobalState().computedRequiresReaction) {\r\n console.warn(\"invoking a computedFn from outside an reactive context won't be memoized, unless keepAlive is set\");\r\n memoWarned = true;\r\n }\r\n return fn.apply(this, args);\r\n }\r\n // create new entry\r\n var latestValue;\r\n var c = computed(function () {\r\n return (latestValue = fn.apply(_this, args));\r\n }, __assign$2(__assign$2({}, opts), { name: \"computedFn(\" + (opts.name || fn.name) + \"#\" + ++i + \")\" }));\r\n entry.set(c);\r\n // clean up if no longer observed\r\n if (!opts.keepAlive)\r\n onBecomeUnobserved(c, function () {\r\n d.entry(args).delete();\r\n if (opts.onCleanup)\r\n opts.onCleanup.apply(opts, __spreadArrays$1([latestValue], args));\r\n latestValue = undefined;\r\n });\r\n // return current val\r\n return c.get();\r\n };\r\n}\n\nexport { FULFILLED, IDENTITY, NOOP, ObservableGroupMap, PENDING, REJECTED, ViewModel, addHiddenProp, chunkProcessor, computedFn, createTransformer, createViewModel, deepObserve, expr, fail, fromPromise, fromResource, fromStream, getAllMethodsAndProperties, invariant, isPromiseBasedObservable, keepAlive, lazyObservable, moveItem, now, queueProcessor, resetNowInternalState, toStream };\n","// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis\nfunction getGlobal() {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n }\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n}\nfunction getDevTools() {\n const w = getGlobal();\n if (!!w.__xstate__) {\n return w.__xstate__;\n }\n return undefined;\n}\nfunction registerService(service) {\n if (typeof window === 'undefined') {\n return;\n }\n const devTools = getDevTools();\n if (devTools) {\n devTools.register(service);\n }\n}\nconst devToolsAdapter = service => {\n if (typeof window === 'undefined') {\n return;\n }\n const devTools = getDevTools();\n if (devTools) {\n devTools.register(service);\n }\n};\n\nexport { devToolsAdapter, getGlobal, registerService };\n","import { devToolsAdapter } from '../dev/dist/xstate-dev.esm.js';\n\nclass Mailbox {\n constructor(_process) {\n this._process = _process;\n this._active = false;\n this._current = null;\n this._last = null;\n }\n start() {\n this._active = true;\n this.flush();\n }\n clear() {\n // we can't set _current to null because we might be currently processing\n // and enqueue following clear shouldnt start processing the enqueued item immediately\n if (this._current) {\n this._current.next = null;\n this._last = this._current;\n }\n }\n enqueue(event) {\n const enqueued = {\n value: event,\n next: null\n };\n if (this._current) {\n this._last.next = enqueued;\n this._last = enqueued;\n return;\n }\n this._current = enqueued;\n this._last = enqueued;\n if (this._active) {\n this.flush();\n }\n }\n flush() {\n while (this._current) {\n // atm the given _process is responsible for implementing proper try/catch handling\n // we assume here that this won't throw in a way that can affect this mailbox\n const consumed = this._current;\n this._process(consumed.value);\n this._current = consumed.next;\n }\n this._last = null;\n }\n}\n\nconst STATE_DELIMITER = '.';\nconst TARGETLESS_KEY = '';\nconst NULL_EVENT = '';\nconst STATE_IDENTIFIER = '#';\nconst WILDCARD = '*';\nconst XSTATE_INIT = 'xstate.init';\nconst XSTATE_ERROR = 'xstate.error';\nconst XSTATE_STOP = 'xstate.stop';\n\n/**\n * Returns an event that represents an implicit event that is sent after the\n * specified `delay`.\n *\n * @param delayRef The delay in milliseconds\n * @param id The state node ID where this event is handled\n */\nfunction createAfterEvent(delayRef, id) {\n return {\n type: `xstate.after.${delayRef}.${id}`\n };\n}\n\n/**\n * Returns an event that represents that a final state node has been reached in\n * the parent state node.\n *\n * @param id The final state node's parent state node `id`\n * @param output The data to pass into the event\n */\nfunction createDoneStateEvent(id, output) {\n return {\n type: `xstate.done.state.${id}`,\n output\n };\n}\n\n/**\n * Returns an event that represents that an invoked service has terminated.\n *\n * An invoked service is terminated when it has reached a top-level final state\n * node, but not when it is canceled.\n *\n * @param invokeId The invoked service ID\n * @param output The data to pass into the event\n */\nfunction createDoneActorEvent(invokeId, output) {\n return {\n type: `xstate.done.actor.${invokeId}`,\n output,\n actorId: invokeId\n };\n}\nfunction createErrorActorEvent(id, error) {\n return {\n type: `xstate.error.actor.${id}`,\n error,\n actorId: id\n };\n}\nfunction createInitEvent(input) {\n return {\n type: XSTATE_INIT,\n input\n };\n}\n\n/**\n * This function makes sure that unhandled errors are thrown in a separate\n * macrotask. It allows those errors to be detected by global error handlers and\n * reported to bug tracking services without interrupting our own stack of\n * execution.\n *\n * @param err Error to be thrown\n */\nfunction reportUnhandledError(err) {\n setTimeout(() => {\n throw err;\n });\n}\n\nconst symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();\n\nfunction matchesState(parentStateId, childStateId) {\n const parentStateValue = toStateValue(parentStateId);\n const childStateValue = toStateValue(childStateId);\n if (typeof childStateValue === 'string') {\n if (typeof parentStateValue === 'string') {\n return childStateValue === parentStateValue;\n }\n\n // Parent more specific than child\n return false;\n }\n if (typeof parentStateValue === 'string') {\n return parentStateValue in childStateValue;\n }\n return Object.keys(parentStateValue).every(key => {\n if (!(key in childStateValue)) {\n return false;\n }\n return matchesState(parentStateValue[key], childStateValue[key]);\n });\n}\nfunction toStatePath(stateId) {\n if (isArray(stateId)) {\n return stateId;\n }\n let result = [];\n let segment = '';\n for (let i = 0; i < stateId.length; i++) {\n const char = stateId.charCodeAt(i);\n switch (char) {\n // \\\n case 92:\n // consume the next character\n segment += stateId[i + 1];\n // and skip over it\n i++;\n continue;\n // .\n case 46:\n result.push(segment);\n segment = '';\n continue;\n }\n segment += stateId[i];\n }\n result.push(segment);\n return result;\n}\nfunction toStateValue(stateValue) {\n if (isMachineSnapshot(stateValue)) {\n return stateValue.value;\n }\n if (typeof stateValue !== 'string') {\n return stateValue;\n }\n const statePath = toStatePath(stateValue);\n return pathToStateValue(statePath);\n}\nfunction pathToStateValue(statePath) {\n if (statePath.length === 1) {\n return statePath[0];\n }\n const value = {};\n let marker = value;\n for (let i = 0; i < statePath.length - 1; i++) {\n if (i === statePath.length - 2) {\n marker[statePath[i]] = statePath[i + 1];\n } else {\n const previous = marker;\n marker = {};\n previous[statePath[i]] = marker;\n }\n }\n return value;\n}\nfunction mapValues(collection, iteratee) {\n const result = {};\n const collectionKeys = Object.keys(collection);\n for (let i = 0; i < collectionKeys.length; i++) {\n const key = collectionKeys[i];\n result[key] = iteratee(collection[key], key, collection, i);\n }\n return result;\n}\nfunction toArrayStrict(value) {\n if (isArray(value)) {\n return value;\n }\n return [value];\n}\nfunction toArray(value) {\n if (value === undefined) {\n return [];\n }\n return toArrayStrict(value);\n}\nfunction resolveOutput(mapper, context, event, self) {\n if (typeof mapper === 'function') {\n return mapper({\n context,\n event,\n self\n });\n }\n return mapper;\n}\nfunction isArray(value) {\n return Array.isArray(value);\n}\nfunction isErrorActorEvent(event) {\n return event.type.startsWith('xstate.error.actor');\n}\nfunction toTransitionConfigArray(configLike) {\n return toArrayStrict(configLike).map(transitionLike => {\n if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {\n return {\n target: transitionLike\n };\n }\n return transitionLike;\n });\n}\nfunction normalizeTarget(target) {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n return toArray(target);\n}\nfunction toObserver(nextHandler, errorHandler, completionHandler) {\n const isObserver = typeof nextHandler === 'object';\n const self = isObserver ? nextHandler : undefined;\n return {\n next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),\n error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),\n complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)\n };\n}\nfunction createInvokeId(stateNodeId, index) {\n return `${index}.${stateNodeId}`;\n}\nfunction resolveReferencedActor(machine, src) {\n const match = src.match(/^xstate\\.invoke\\.(\\d+)\\.(.*)/);\n if (!match) {\n return machine.implementations.actors[src];\n }\n const [, indexStr, nodeId] = match;\n const node = machine.getStateNodeById(nodeId);\n const invokeConfig = node.config.invoke;\n return (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;\n}\nfunction getAllOwnEventDescriptors(snapshot) {\n return [...new Set([...snapshot._nodes.flatMap(sn => sn.ownEvents)])];\n}\n\nfunction createScheduledEventId(actorRef, id) {\n return `${actorRef.sessionId}.${id}`;\n}\nlet idCounter = 0;\nfunction createSystem(rootActor, options) {\n const children = new Map();\n const keyedActors = new Map();\n const reverseKeyedActors = new WeakMap();\n const inspectionObservers = new Set();\n const timerMap = {};\n const {\n clock,\n logger\n } = options;\n const scheduler = {\n schedule: (source, target, event, delay, id = Math.random().toString(36).slice(2)) => {\n const scheduledEvent = {\n source,\n target,\n event,\n delay,\n id,\n startedAt: Date.now()\n };\n const scheduledEventId = createScheduledEventId(source, id);\n system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;\n const timeout = clock.setTimeout(() => {\n delete timerMap[scheduledEventId];\n delete system._snapshot._scheduledEvents[scheduledEventId];\n system._relay(source, target, event);\n }, delay);\n timerMap[scheduledEventId] = timeout;\n },\n cancel: (source, id) => {\n const scheduledEventId = createScheduledEventId(source, id);\n const timeout = timerMap[scheduledEventId];\n delete timerMap[scheduledEventId];\n delete system._snapshot._scheduledEvents[scheduledEventId];\n if (timeout !== undefined) {\n clock.clearTimeout(timeout);\n }\n },\n cancelAll: actorRef => {\n for (const scheduledEventId in system._snapshot._scheduledEvents) {\n const scheduledEvent = system._snapshot._scheduledEvents[scheduledEventId];\n if (scheduledEvent.source === actorRef) {\n scheduler.cancel(actorRef, scheduledEvent.id);\n }\n }\n }\n };\n const sendInspectionEvent = event => {\n if (!inspectionObservers.size) {\n return;\n }\n const resolvedInspectionEvent = {\n ...event,\n rootId: rootActor.sessionId\n };\n inspectionObservers.forEach(observer => observer.next?.(resolvedInspectionEvent));\n };\n const system = {\n _snapshot: {\n _scheduledEvents: (options?.snapshot && options.snapshot.scheduler) ?? {}\n },\n _bookId: () => `x:${idCounter++}`,\n _register: (sessionId, actorRef) => {\n children.set(sessionId, actorRef);\n return sessionId;\n },\n _unregister: actorRef => {\n children.delete(actorRef.sessionId);\n const systemId = reverseKeyedActors.get(actorRef);\n if (systemId !== undefined) {\n keyedActors.delete(systemId);\n reverseKeyedActors.delete(actorRef);\n }\n },\n get: systemId => {\n return keyedActors.get(systemId);\n },\n _set: (systemId, actorRef) => {\n const existing = keyedActors.get(systemId);\n if (existing && existing !== actorRef) {\n throw new Error(`Actor with system ID '${systemId}' already exists.`);\n }\n keyedActors.set(systemId, actorRef);\n reverseKeyedActors.set(actorRef, systemId);\n },\n inspect: observerOrFn => {\n const observer = toObserver(observerOrFn);\n inspectionObservers.add(observer);\n return {\n unsubscribe() {\n inspectionObservers.delete(observer);\n }\n };\n },\n _sendInspectionEvent: sendInspectionEvent,\n _relay: (source, target, event) => {\n system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: source,\n actorRef: target,\n event\n });\n target._send(event);\n },\n scheduler,\n getSnapshot: () => {\n return {\n _scheduledEvents: {\n ...system._snapshot._scheduledEvents\n }\n };\n },\n start: () => {\n const scheduledEvents = system._snapshot._scheduledEvents;\n system._snapshot._scheduledEvents = {};\n for (const scheduledId in scheduledEvents) {\n const {\n source,\n target,\n event,\n delay,\n id\n } = scheduledEvents[scheduledId];\n scheduler.schedule(source, target, event, delay, id);\n }\n },\n _clock: clock,\n _logger: logger\n };\n return system;\n}\n\nconst $$ACTOR_TYPE = 1;\n\n// those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync\nlet ProcessingStatus = /*#__PURE__*/function (ProcessingStatus) {\n ProcessingStatus[ProcessingStatus[\"NotStarted\"] = 0] = \"NotStarted\";\n ProcessingStatus[ProcessingStatus[\"Running\"] = 1] = \"Running\";\n ProcessingStatus[ProcessingStatus[\"Stopped\"] = 2] = \"Stopped\";\n return ProcessingStatus;\n}({});\nconst defaultOptions = {\n clock: {\n setTimeout: (fn, ms) => {\n return setTimeout(fn, ms);\n },\n clearTimeout: id => {\n return clearTimeout(id);\n }\n },\n logger: console.log.bind(console),\n devTools: false\n};\n\n/**\n * An Actor is a running process that can receive events, send events and change\n * its behavior based on the events it receives, which can cause effects outside\n * of the actor. When you run a state machine, it becomes an actor.\n */\nclass Actor {\n /**\n * Creates a new actor instance for the given logic with the provided options,\n * if any.\n *\n * @param logic The logic to create an actor from\n * @param options Actor options\n */\n constructor(logic, options) {\n this.logic = logic;\n /** The current internal state of the actor. */\n this._snapshot = void 0;\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n */\n this.clock = void 0;\n this.options = void 0;\n /** The unique identifier for this actor relative to its parent. */\n this.id = void 0;\n this.mailbox = new Mailbox(this._process.bind(this));\n this.observers = new Set();\n this.eventListeners = new Map();\n this.logger = void 0;\n /** @internal */\n this._processingStatus = ProcessingStatus.NotStarted;\n // Actor Ref\n this._parent = void 0;\n /** @internal */\n this._syncSnapshot = void 0;\n this.ref = void 0;\n // TODO: add typings for system\n this._actorScope = void 0;\n this._systemId = void 0;\n /** The globally unique process ID for this invocation. */\n this.sessionId = void 0;\n /** The system to which this actor belongs. */\n this.system = void 0;\n this._doneEvent = void 0;\n this.src = void 0;\n // array of functions to defer\n this._deferred = [];\n const resolvedOptions = {\n ...defaultOptions,\n ...options\n };\n const {\n clock,\n logger,\n parent,\n syncSnapshot,\n id,\n systemId,\n inspect\n } = resolvedOptions;\n this.system = parent ? parent.system : createSystem(this, {\n clock,\n logger\n });\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n this.sessionId = this.system._bookId();\n this.id = id ?? this.sessionId;\n this.logger = options?.logger ?? this.system._logger;\n this.clock = options?.clock ?? this.system._clock;\n this._parent = parent;\n this._syncSnapshot = syncSnapshot;\n this.options = resolvedOptions;\n this.src = resolvedOptions.src ?? logic;\n this.ref = this;\n this._actorScope = {\n self: this,\n id: this.id,\n sessionId: this.sessionId,\n logger: this.logger,\n defer: fn => {\n this._deferred.push(fn);\n },\n system: this.system,\n stopChild: child => {\n if (child._parent !== this) {\n throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);\n }\n child._stop();\n },\n emit: emittedEvent => {\n const listeners = this.eventListeners.get(emittedEvent.type);\n const wildcardListener = this.eventListeners.get('*');\n if (!listeners && !wildcardListener) {\n return;\n }\n const allListeners = new Set([...(listeners ? listeners.values() : []), ...(wildcardListener ? wildcardListener.values() : [])]);\n for (const handler of Array.from(allListeners)) {\n handler(emittedEvent);\n }\n }\n };\n\n // Ensure that the send method is bound to this Actor instance\n // if destructured\n this.send = this.send.bind(this);\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this\n });\n if (systemId) {\n this._systemId = systemId;\n this.system._set(systemId, this);\n }\n this._initState(options?.snapshot ?? options?.state);\n if (systemId && this._snapshot.status !== 'active') {\n this.system._unregister(this);\n }\n }\n _initState(persistedState) {\n try {\n this._snapshot = persistedState ? this.logic.restoreSnapshot ? this.logic.restoreSnapshot(persistedState, this._actorScope) : persistedState : this.logic.getInitialSnapshot(this._actorScope, this.options?.input);\n } catch (err) {\n // if we get here then it means that we assign a value to this._snapshot that is not of the correct type\n // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible\n // so right now this is a lie of sorts\n this._snapshot = {\n status: 'error',\n output: undefined,\n error: err\n };\n }\n }\n update(snapshot, event) {\n // Update state\n this._snapshot = snapshot;\n\n // Execute deferred effects\n let deferredFn;\n while (deferredFn = this._deferred.shift()) {\n try {\n deferredFn();\n } catch (err) {\n // this error can only be caught when executing *initial* actions\n // it's the only time when we call actions provided by the user through those deferreds\n // when the actor is already running we always execute them synchronously while transitioning\n // no \"builtin deferred\" should actually throw an error since they are either safe\n // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox\n this._deferred.length = 0;\n this._snapshot = {\n ...snapshot,\n status: 'error',\n error: err\n };\n }\n }\n switch (this._snapshot.status) {\n case 'active':\n for (const observer of this.observers) {\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n break;\n case 'done':\n // next observers are meant to be notified about done snapshots\n // this can be seen as something that is different from how observable work\n // but with observables `complete` callback is called without any arguments\n // it's more ergonomic for XState to treat a done snapshot as a \"next\" value\n // and the completion event as something that is separate,\n // something that merely follows emitting that done snapshot\n for (const observer of this.observers) {\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n this._stopProcedure();\n this._complete();\n this._doneEvent = createDoneActorEvent(this.id, this._snapshot.output);\n if (this._parent) {\n this.system._relay(this, this._parent, this._doneEvent);\n }\n break;\n case 'error':\n this._error(this._snapshot.error);\n break;\n }\n this.system._sendInspectionEvent({\n type: '@xstate.snapshot',\n actorRef: this,\n event,\n snapshot\n });\n }\n\n /**\n * Subscribe an observer to an actor’s snapshot values.\n *\n * @remarks\n * The observer will receive the actor’s snapshot value when it is emitted.\n * The observer can be:\n *\n * - A plain function that receives the latest snapshot, or\n * - An observer object whose `.next(snapshot)` method receives the latest\n * snapshot\n *\n * @example\n *\n * ```ts\n * // Observer as a plain function\n * const subscription = actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * ```\n *\n * @example\n *\n * ```ts\n * // Observer as an object\n * const subscription = actor.subscribe({\n * next(snapshot) {\n * console.log(snapshot);\n * },\n * error(err) {\n * // ...\n * },\n * complete() {\n * // ...\n * }\n * });\n * ```\n *\n * The return value of `actor.subscribe(observer)` is a subscription object\n * that has an `.unsubscribe()` method. You can call\n * `subscription.unsubscribe()` to unsubscribe the observer:\n *\n * @example\n *\n * ```ts\n * const subscription = actor.subscribe((snapshot) => {\n * // ...\n * });\n *\n * // Unsubscribe the observer\n * subscription.unsubscribe();\n * ```\n *\n * When the actor is stopped, all of its observers will automatically be\n * unsubscribed.\n *\n * @param observer - Either a plain function that receives the latest\n * snapshot, or an observer object whose `.next(snapshot)` method receives\n * the latest snapshot\n */\n\n subscribe(nextListenerOrObserver, errorListener, completeListener) {\n const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);\n if (this._processingStatus !== ProcessingStatus.Stopped) {\n this.observers.add(observer);\n } else {\n switch (this._snapshot.status) {\n case 'done':\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n break;\n case 'error':\n {\n const err = this._snapshot.error;\n if (!observer.error) {\n reportUnhandledError(err);\n } else {\n try {\n observer.error(err);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n break;\n }\n }\n }\n return {\n unsubscribe: () => {\n this.observers.delete(observer);\n }\n };\n }\n on(type, handler) {\n let listeners = this.eventListeners.get(type);\n if (!listeners) {\n listeners = new Set();\n this.eventListeners.set(type, listeners);\n }\n const wrappedHandler = handler.bind(undefined);\n listeners.add(wrappedHandler);\n return {\n unsubscribe: () => {\n listeners.delete(wrappedHandler);\n }\n };\n }\n\n /** Starts the Actor from the initial state */\n start() {\n if (this._processingStatus === ProcessingStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n }\n if (this._syncSnapshot) {\n this.subscribe({\n next: snapshot => {\n if (snapshot.status === 'active') {\n this.system._relay(this, this._parent, {\n type: `xstate.snapshot.${this.id}`,\n snapshot\n });\n }\n },\n error: () => {}\n });\n }\n this.system._register(this.sessionId, this);\n if (this._systemId) {\n this.system._set(this._systemId, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n // TODO: this isn't correct when rehydrating\n const initEvent = createInitEvent(this.options.input);\n this.system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: this._parent,\n actorRef: this,\n event: initEvent\n });\n const status = this._snapshot.status;\n switch (status) {\n case 'done':\n // a state machine can be \"done\" upon initialization (it could reach a final state using initial microsteps)\n // we still need to complete observers, flush deferreds etc\n this.update(this._snapshot, initEvent);\n // TODO: rethink cleanup of observers, mailbox, etc\n return this;\n case 'error':\n this._error(this._snapshot.error);\n return this;\n }\n if (!this._parent) {\n this.system.start();\n }\n if (this.logic.start) {\n try {\n this.logic.start(this._snapshot, this._actorScope);\n } catch (err) {\n this._snapshot = {\n ...this._snapshot,\n status: 'error',\n error: err\n };\n this._error(err);\n return this;\n }\n }\n\n // TODO: this notifies all subscribers but usually this is redundant\n // there is no real change happening here\n // we need to rethink if this needs to be refactored\n this.update(this._snapshot, initEvent);\n if (this.options.devTools) {\n this.attachDevTools();\n }\n this.mailbox.start();\n return this;\n }\n _process(event) {\n let nextState;\n let caughtError;\n try {\n nextState = this.logic.transition(this._snapshot, event, this._actorScope);\n } catch (err) {\n // we wrap it in a box so we can rethrow it later even if falsy value gets caught here\n caughtError = {\n err\n };\n }\n if (caughtError) {\n const {\n err\n } = caughtError;\n this._snapshot = {\n ...this._snapshot,\n status: 'error',\n error: err\n };\n this._error(err);\n return;\n }\n this.update(nextState, event);\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n _stop() {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n this.mailbox.clear();\n if (this._processingStatus === ProcessingStatus.NotStarted) {\n this._processingStatus = ProcessingStatus.Stopped;\n return this;\n }\n this.mailbox.enqueue({\n type: XSTATE_STOP\n });\n return this;\n }\n\n /** Stops the Actor and unsubscribe all listeners. */\n stop() {\n if (this._parent) {\n throw new Error('A non-root actor cannot be stopped directly.');\n }\n return this._stop();\n }\n _complete() {\n for (const observer of this.observers) {\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n this.observers.clear();\n }\n _reportError(err) {\n if (!this.observers.size) {\n if (!this._parent) {\n reportUnhandledError(err);\n }\n return;\n }\n let reportError = false;\n for (const observer of this.observers) {\n const errorListener = observer.error;\n reportError ||= !errorListener;\n try {\n errorListener?.(err);\n } catch (err2) {\n reportUnhandledError(err2);\n }\n }\n this.observers.clear();\n if (reportError) {\n reportUnhandledError(err);\n }\n }\n _error(err) {\n this._stopProcedure();\n this._reportError(err);\n if (this._parent) {\n this.system._relay(this, this._parent, createErrorActorEvent(this.id, err));\n }\n }\n // TODO: atm children don't belong entirely to the actor so\n // in a way - it's not even super aware of them\n // so we can't stop them from here but we really should!\n // right now, they are being stopped within the machine's transition\n // but that could throw and leave us with \"orphaned\" active actors\n _stopProcedure() {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return this;\n }\n\n // Cancel all delayed events\n this.system.scheduler.cancelAll(this);\n\n // TODO: mailbox.reset\n this.mailbox.clear();\n // TODO: after `stop` we must prepare ourselves for receiving events again\n // events sent *after* stop signal must be queued\n // it seems like this should be the common behavior for all of our consumers\n // so perhaps this should be unified somehow for all of them\n this.mailbox = new Mailbox(this._process.bind(this));\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n return this;\n }\n\n /** @internal */\n _send(event) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return;\n }\n this.mailbox.enqueue(event);\n }\n\n /**\n * Sends an event to the running Actor to trigger a transition.\n *\n * @param event The event to send\n */\n send(event) {\n this.system._relay(undefined, this, event);\n }\n attachDevTools() {\n const {\n devTools\n } = this.options;\n if (devTools) {\n const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;\n resolvedDevToolsAdapter(this);\n }\n }\n toJSON() {\n return {\n xstate$$type: $$ACTOR_TYPE,\n id: this.id\n };\n }\n\n /**\n * Obtain the internal state of the actor, which can be persisted.\n *\n * @remarks\n * The internal state can be persisted from any actor, not only machines.\n *\n * Note that the persisted state is not the same as the snapshot from\n * {@link Actor.getSnapshot}. Persisted state represents the internal state of\n * the actor, while snapshots represent the actor's last emitted value.\n *\n * Can be restored with {@link ActorOptions.state}\n * @see https://stately.ai/docs/persistence\n */\n\n getPersistedSnapshot(options) {\n return this.logic.getPersistedSnapshot(this._snapshot, options);\n }\n [symbolObservable]() {\n return this;\n }\n\n /**\n * Read an actor’s snapshot synchronously.\n *\n * @remarks\n * The snapshot represent an actor's last emitted value.\n *\n * When an actor receives an event, its internal state may change. An actor\n * may emit a snapshot when a state transition occurs.\n *\n * Note that some actors, such as callback actors generated with\n * `fromCallback`, will not emit snapshots.\n * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.\n * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).\n */\n getSnapshot() {\n return this._snapshot;\n }\n}\n/**\n * Creates a new actor instance for the given actor logic with the provided\n * options, if any.\n *\n * @remarks\n * When you create an actor from actor logic via `createActor(logic)`, you\n * implicitly create an actor system where the created actor is the root actor.\n * Any actors spawned from this root actor and its descendants are part of that\n * actor system.\n * @example\n *\n * ```ts\n * import { createActor } from 'xstate';\n * import { someActorLogic } from './someActorLogic.ts';\n *\n * // Creating the actor, which implicitly creates an actor system with itself as the root actor\n * const actor = createActor(someActorLogic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n *\n * // Actors must be started by calling `actor.start()`, which will also start the actor system.\n * actor.start();\n *\n * // Actors can receive events\n * actor.send({ type: 'someEvent' });\n *\n * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.\n * actor.stop();\n * ```\n *\n * @param logic - The actor logic to create an actor from. For a state machine\n * actor logic creator, see {@link createMachine}. Other actor logic creators\n * include {@link fromCallback}, {@link fromEventObservable},\n * {@link fromObservable}, {@link fromPromise}, and {@link fromTransition}.\n * @param options - Actor options\n */\nfunction createActor(logic, ...[options]) {\n return new Actor(logic, options);\n}\n\n/**\n * Creates a new Interpreter instance for the given machine with the provided\n * options, if any.\n *\n * @deprecated Use `createActor` instead\n * @alias\n */\nconst interpret = createActor;\n\n/**\n * @deprecated Use `Actor` instead.\n * @alias\n */\n\nfunction resolveCancel(_, snapshot, actionArgs, actionParams, {\n sendId\n}) {\n const resolvedSendId = typeof sendId === 'function' ? sendId(actionArgs, actionParams) : sendId;\n return [snapshot, resolvedSendId];\n}\nfunction executeCancel(actorScope, resolvedSendId) {\n actorScope.defer(() => {\n actorScope.system.scheduler.cancel(actorScope.self, resolvedSendId);\n });\n}\n/**\n * Cancels a delayed `sendTo(...)` action that is waiting to be executed. The\n * canceled `sendTo(...)` action will not send its event or execute, unless the\n * `delay` has already elapsed before `cancel(...)` is called.\n *\n * @example\n *\n * ```ts\n * import { createMachine, sendTo, cancel } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * on: {\n * sendEvent: {\n * actions: sendTo(\n * 'some-actor',\n * { type: 'someEvent' },\n * {\n * id: 'some-id',\n * delay: 1000\n * }\n * )\n * },\n * cancelEvent: {\n * actions: cancel('some-id')\n * }\n * }\n * });\n * ```\n *\n * @param sendId The `id` of the `sendTo(...)` action to cancel.\n */\nfunction cancel(sendId) {\n function cancel(args, params) {\n }\n cancel.type = 'xstate.cancel';\n cancel.sendId = sendId;\n cancel.resolve = resolveCancel;\n cancel.execute = executeCancel;\n return cancel;\n}\n\nfunction checkStateIn(snapshot, _, {\n stateValue\n}) {\n if (typeof stateValue === 'string' && isStateId(stateValue)) {\n const target = snapshot.machine.getStateNodeById(stateValue);\n return snapshot._nodes.some(sn => sn === target);\n }\n return snapshot.matches(stateValue);\n}\nfunction stateIn(stateValue) {\n function stateIn(args, params) {\n return false;\n }\n stateIn.check = checkStateIn;\n stateIn.stateValue = stateValue;\n return stateIn;\n}\nfunction checkNot(snapshot, {\n context,\n event\n}, {\n guards\n}) {\n return !evaluateGuard(guards[0], context, event, snapshot);\n}\n\n/**\n * Higher-order guard that evaluates to `true` if the `guard` passed to it\n * evaluates to `false`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, not } from 'xstate';\n *\n * const machine = setup({\n * guards: {\n * someNamedGuard: () => false\n * }\n * }).createMachine({\n * on: {\n * someEvent: {\n * guard: not('someNamedGuard'),\n * actions: () => {\n * // will be executed if guard in `not(...)`\n * // evaluates to `false`\n * }\n * }\n * }\n * });\n * ```\n *\n * @returns A guard\n */\nfunction not(guard) {\n function not(args, params) {\n return false;\n }\n not.check = checkNot;\n not.guards = [guard];\n return not;\n}\nfunction checkAnd(snapshot, {\n context,\n event\n}, {\n guards\n}) {\n return guards.every(guard => evaluateGuard(guard, context, event, snapshot));\n}\n\n/**\n * Higher-order guard that evaluates to `true` if all `guards` passed to it\n * evaluate to `true`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, and } from 'xstate';\n *\n * const machine = setup({\n * guards: {\n * someNamedGuard: () => true\n * }\n * }).createMachine({\n * on: {\n * someEvent: {\n * guard: and([({ context }) => context.value > 0, 'someNamedGuard']),\n * actions: () => {\n * // will be executed if all guards in `and(...)`\n * // evaluate to true\n * }\n * }\n * }\n * });\n * ```\n *\n * @returns A guard action object\n */\nfunction and(guards) {\n function and(args, params) {\n return false;\n }\n and.check = checkAnd;\n and.guards = guards;\n return and;\n}\nfunction checkOr(snapshot, {\n context,\n event\n}, {\n guards\n}) {\n return guards.some(guard => evaluateGuard(guard, context, event, snapshot));\n}\n\n/**\n * Higher-order guard that evaluates to `true` if any of the `guards` passed to\n * it evaluate to `true`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, or } from 'xstate';\n *\n * const machine = setup({\n * guards: {\n * someNamedGuard: () => true\n * }\n * }).createMachine({\n * on: {\n * someEvent: {\n * guard: or([({ context }) => context.value > 0, 'someNamedGuard']),\n * actions: () => {\n * // will be executed if any of the guards in `or(...)`\n * // evaluate to true\n * }\n * }\n * }\n * });\n * ```\n *\n * @returns A guard action object\n */\nfunction or(guards) {\n function or(args, params) {\n return false;\n }\n or.check = checkOr;\n or.guards = guards;\n return or;\n}\n\n// TODO: throw on cycles (depth check should be enough)\nfunction evaluateGuard(guard, context, event, snapshot) {\n const {\n machine\n } = snapshot;\n const isInline = typeof guard === 'function';\n const resolved = isInline ? guard : machine.implementations.guards[typeof guard === 'string' ? guard : guard.type];\n if (!isInline && !resolved) {\n throw new Error(`Guard '${typeof guard === 'string' ? guard : guard.type}' is not implemented.'.`);\n }\n if (typeof resolved !== 'function') {\n return evaluateGuard(resolved, context, event, snapshot);\n }\n const guardArgs = {\n context,\n event\n };\n const guardParams = isInline || typeof guard === 'string' ? undefined : 'params' in guard ? typeof guard.params === 'function' ? guard.params({\n context,\n event\n }) : guard.params : undefined;\n if (!('check' in resolved)) {\n // the existing type of `.guards` assumes non-nullable `TExpressionGuard`\n // inline guards expect `TExpressionGuard` to be set to `undefined`\n // it's fine to cast this here, our logic makes sure that we call those 2 \"variants\" correctly\n return resolved(guardArgs, guardParams);\n }\n const builtinGuard = resolved;\n return builtinGuard.check(snapshot, guardArgs, resolved // this holds all params\n );\n}\n\nfunction resolveRaise(_, snapshot, args, actionParams, {\n event: eventOrExpr,\n id,\n delay\n}, {\n internalQueue\n}) {\n const delaysMap = snapshot.machine.implementations.delays;\n if (typeof eventOrExpr === 'string') {\n throw new Error(`Only event objects may be used with raise; use raise({ type: \"${eventOrExpr}\" }) instead`);\n }\n const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;\n let resolvedDelay;\n if (typeof delay === 'string') {\n const configDelay = delaysMap && delaysMap[delay];\n resolvedDelay = typeof configDelay === 'function' ? configDelay(args, actionParams) : configDelay;\n } else {\n resolvedDelay = typeof delay === 'function' ? delay(args, actionParams) : delay;\n }\n if (typeof resolvedDelay !== 'number') {\n internalQueue.push(resolvedEvent);\n }\n return [snapshot, {\n event: resolvedEvent,\n id,\n delay: resolvedDelay\n }];\n}\nfunction executeRaise(actorScope, params) {\n const {\n event,\n delay,\n id\n } = params;\n if (typeof delay === 'number') {\n actorScope.defer(() => {\n const self = actorScope.self;\n actorScope.system.scheduler.schedule(self, self, event, delay, id);\n });\n return;\n }\n}\n/**\n * Raises an event. This places the event in the internal event queue, so that\n * the event is immediately consumed by the machine in the current step.\n *\n * @param eventType The event to raise.\n */\nfunction raise(eventOrExpr, options) {\n function raise(args, params) {\n }\n raise.type = 'xstate.raise';\n raise.event = eventOrExpr;\n raise.id = options?.id;\n raise.delay = options?.delay;\n raise.resolve = resolveRaise;\n raise.execute = executeRaise;\n return raise;\n}\n\nfunction resolveSpawn(actorScope, snapshot, actionArgs, _actionParams, {\n id,\n systemId,\n src,\n input,\n syncSnapshot\n}) {\n const logic = typeof src === 'string' ? resolveReferencedActor(snapshot.machine, src) : src;\n const resolvedId = typeof id === 'function' ? id(actionArgs) : id;\n let actorRef;\n if (logic) {\n actorRef = createActor(logic, {\n id: resolvedId,\n src,\n parent: actorScope.self,\n syncSnapshot,\n systemId,\n input: typeof input === 'function' ? input({\n context: snapshot.context,\n event: actionArgs.event,\n self: actorScope.self\n }) : input\n });\n }\n return [cloneMachineSnapshot(snapshot, {\n children: {\n ...snapshot.children,\n [resolvedId]: actorRef\n }\n }), {\n id,\n actorRef\n }];\n}\nfunction executeSpawn(actorScope, {\n id,\n actorRef\n}) {\n if (!actorRef) {\n return;\n }\n actorScope.defer(() => {\n if (actorRef._processingStatus === ProcessingStatus.Stopped) {\n return;\n }\n actorRef.start();\n });\n}\nfunction spawnChild(...[src, {\n id,\n systemId,\n input,\n syncSnapshot = false\n} = {}]) {\n function spawnChild(args, params) {\n }\n spawnChild.type = 'snapshot.spawnChild';\n spawnChild.id = id;\n spawnChild.systemId = systemId;\n spawnChild.src = src;\n spawnChild.input = input;\n spawnChild.syncSnapshot = syncSnapshot;\n spawnChild.resolve = resolveSpawn;\n spawnChild.execute = executeSpawn;\n return spawnChild;\n}\n\nfunction resolveStop(_, snapshot, args, actionParams, {\n actorRef\n}) {\n const actorRefOrString = typeof actorRef === 'function' ? actorRef(args, actionParams) : actorRef;\n const resolvedActorRef = typeof actorRefOrString === 'string' ? snapshot.children[actorRefOrString] : actorRefOrString;\n let children = snapshot.children;\n if (resolvedActorRef) {\n children = {\n ...children\n };\n delete children[resolvedActorRef.id];\n }\n return [cloneMachineSnapshot(snapshot, {\n children\n }), resolvedActorRef];\n}\nfunction executeStop(actorScope, actorRef) {\n if (!actorRef) {\n return;\n }\n\n // we need to eagerly unregister it here so a new actor with the same systemId can be registered immediately\n // since we defer actual stopping of the actor but we don't defer actor creations (and we can't do that)\n // this could throw on `systemId` collision, for example, when dealing with reentering transitions\n actorScope.system._unregister(actorRef);\n\n // this allows us to prevent an actor from being started if it gets stopped within the same macrostep\n // this can happen, for example, when the invoking state is being exited immediately by an always transition\n if (actorRef._processingStatus !== ProcessingStatus.Running) {\n actorScope.stopChild(actorRef);\n return;\n }\n // stopping a child enqueues a stop event in the child actor's mailbox\n // we need for all of the already enqueued events to be processed before we stop the child\n // the parent itself might want to send some events to a child (for example from exit actions on the invoking state)\n // and we don't want to ignore those events\n actorScope.defer(() => {\n actorScope.stopChild(actorRef);\n });\n}\n/**\n * Stops a child actor.\n *\n * @param actorRef The actor to stop.\n */\nfunction stopChild(actorRef) {\n function stop(args, params) {\n }\n stop.type = 'xstate.stopChild';\n stop.actorRef = actorRef;\n stop.resolve = resolveStop;\n stop.execute = executeStop;\n return stop;\n}\n\n/**\n * Stops a child actor.\n *\n * @deprecated Use `stopChild(...)` instead\n * @alias\n */\nconst stop = stopChild;\n\nconst isAtomicStateNode = stateNode => stateNode.type === 'atomic' || stateNode.type === 'final';\nfunction getChildren(stateNode) {\n return Object.values(stateNode.states).filter(sn => sn.type !== 'history');\n}\nfunction getProperAncestors(stateNode, toStateNode) {\n const ancestors = [];\n if (toStateNode === stateNode) {\n return ancestors;\n }\n\n // add all ancestors\n let m = stateNode.parent;\n while (m && m !== toStateNode) {\n ancestors.push(m);\n m = m.parent;\n }\n return ancestors;\n}\nfunction getAllStateNodes(stateNodes) {\n const nodeSet = new Set(stateNodes);\n const adjList = getAdjList(nodeSet);\n\n // add descendants\n for (const s of nodeSet) {\n // if previously active, add existing child nodes\n if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {\n getInitialStateNodesWithTheirAncestors(s).forEach(sn => nodeSet.add(sn));\n } else {\n if (s.type === 'parallel') {\n for (const child of getChildren(s)) {\n if (child.type === 'history') {\n continue;\n }\n if (!nodeSet.has(child)) {\n const initialStates = getInitialStateNodesWithTheirAncestors(child);\n for (const initialStateNode of initialStates) {\n nodeSet.add(initialStateNode);\n }\n }\n }\n }\n }\n }\n\n // add all ancestors\n for (const s of nodeSet) {\n let m = s.parent;\n while (m) {\n nodeSet.add(m);\n m = m.parent;\n }\n }\n return nodeSet;\n}\nfunction getValueFromAdj(baseNode, adjList) {\n const childStateNodes = adjList.get(baseNode);\n if (!childStateNodes) {\n return {}; // todo: fix?\n }\n\n if (baseNode.type === 'compound') {\n const childStateNode = childStateNodes[0];\n if (childStateNode) {\n if (isAtomicStateNode(childStateNode)) {\n return childStateNode.key;\n }\n } else {\n return {};\n }\n }\n const stateValue = {};\n for (const childStateNode of childStateNodes) {\n stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);\n }\n return stateValue;\n}\nfunction getAdjList(stateNodes) {\n const adjList = new Map();\n for (const s of stateNodes) {\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n if (s.parent) {\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n adjList.get(s.parent).push(s);\n }\n }\n return adjList;\n}\nfunction getStateValue(rootNode, stateNodes) {\n const config = getAllStateNodes(stateNodes);\n return getValueFromAdj(rootNode, getAdjList(config));\n}\nfunction isInFinalState(stateNodeSet, stateNode) {\n if (stateNode.type === 'compound') {\n return getChildren(stateNode).some(s => s.type === 'final' && stateNodeSet.has(s));\n }\n if (stateNode.type === 'parallel') {\n return getChildren(stateNode).every(sn => isInFinalState(stateNodeSet, sn));\n }\n return stateNode.type === 'final';\n}\nconst isStateId = str => str[0] === STATE_IDENTIFIER;\nfunction getCandidates(stateNode, receivedEventType) {\n const candidates = stateNode.transitions.get(receivedEventType) || [...stateNode.transitions.keys()].filter(eventDescriptor => {\n // check if transition is a wildcard transition,\n // which matches any non-transient events\n if (eventDescriptor === WILDCARD) {\n return true;\n }\n if (!eventDescriptor.endsWith('.*')) {\n return false;\n }\n const partialEventTokens = eventDescriptor.split('.');\n const eventTokens = receivedEventType.split('.');\n for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {\n const partialEventToken = partialEventTokens[tokenIndex];\n const eventToken = eventTokens[tokenIndex];\n if (partialEventToken === '*') {\n const isLastToken = tokenIndex === partialEventTokens.length - 1;\n return isLastToken;\n }\n if (partialEventToken !== eventToken) {\n return false;\n }\n }\n return true;\n }).sort((a, b) => b.length - a.length).flatMap(key => stateNode.transitions.get(key));\n return candidates;\n}\n\n/** All delayed transitions from the config. */\nfunction getDelayedTransitions(stateNode) {\n const afterConfig = stateNode.config.after;\n if (!afterConfig) {\n return [];\n }\n const mutateEntryExit = (delay, i) => {\n const afterEvent = createAfterEvent(delay, stateNode.id);\n const eventType = afterEvent.type;\n stateNode.entry.push(raise(afterEvent, {\n id: eventType,\n delay\n }));\n stateNode.exit.push(cancel(eventType));\n return eventType;\n };\n const delayedTransitions = Object.keys(afterConfig).flatMap((delay, i) => {\n const configTransition = afterConfig[delay];\n const resolvedTransition = typeof configTransition === 'string' ? {\n target: configTransition\n } : configTransition;\n const resolvedDelay = Number.isNaN(+delay) ? delay : +delay;\n const eventType = mutateEntryExit(resolvedDelay);\n return toArray(resolvedTransition).map(transition => ({\n ...transition,\n event: eventType,\n delay: resolvedDelay\n }));\n });\n return delayedTransitions.map(delayedTransition => {\n const {\n delay\n } = delayedTransition;\n return {\n ...formatTransition(stateNode, delayedTransition.event, delayedTransition),\n delay\n };\n });\n}\nfunction formatTransition(stateNode, descriptor, transitionConfig) {\n const normalizedTarget = normalizeTarget(transitionConfig.target);\n const reenter = transitionConfig.reenter ?? false;\n const target = resolveTarget(stateNode, normalizedTarget);\n const transition = {\n ...transitionConfig,\n actions: toArray(transitionConfig.actions),\n guard: transitionConfig.guard,\n target,\n source: stateNode,\n reenter,\n eventType: descriptor,\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: target ? target.map(t => `#${t.id}`) : undefined\n })\n };\n return transition;\n}\nfunction formatTransitions(stateNode) {\n const transitions = new Map();\n if (stateNode.config.on) {\n for (const descriptor of Object.keys(stateNode.config.on)) {\n if (descriptor === NULL_EVENT) {\n throw new Error('Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.');\n }\n const transitionsConfig = stateNode.config.on[descriptor];\n transitions.set(descriptor, toTransitionConfigArray(transitionsConfig).map(t => formatTransition(stateNode, descriptor, t)));\n }\n }\n if (stateNode.config.onDone) {\n const descriptor = `xstate.done.state.${stateNode.id}`;\n transitions.set(descriptor, toTransitionConfigArray(stateNode.config.onDone).map(t => formatTransition(stateNode, descriptor, t)));\n }\n for (const invokeDef of stateNode.invoke) {\n if (invokeDef.onDone) {\n const descriptor = `xstate.done.actor.${invokeDef.id}`;\n transitions.set(descriptor, toTransitionConfigArray(invokeDef.onDone).map(t => formatTransition(stateNode, descriptor, t)));\n }\n if (invokeDef.onError) {\n const descriptor = `xstate.error.actor.${invokeDef.id}`;\n transitions.set(descriptor, toTransitionConfigArray(invokeDef.onError).map(t => formatTransition(stateNode, descriptor, t)));\n }\n if (invokeDef.onSnapshot) {\n const descriptor = `xstate.snapshot.${invokeDef.id}`;\n transitions.set(descriptor, toTransitionConfigArray(invokeDef.onSnapshot).map(t => formatTransition(stateNode, descriptor, t)));\n }\n }\n for (const delayedTransition of stateNode.after) {\n let existing = transitions.get(delayedTransition.eventType);\n if (!existing) {\n existing = [];\n transitions.set(delayedTransition.eventType, existing);\n }\n existing.push(delayedTransition);\n }\n return transitions;\n}\nfunction formatInitialTransition(stateNode, _target) {\n const resolvedTarget = typeof _target === 'string' ? stateNode.states[_target] : _target ? stateNode.states[_target.target] : undefined;\n if (!resolvedTarget && _target) {\n throw new Error(`Initial state node \"${_target}\" not found on parent state node #${stateNode.id}`);\n }\n const transition = {\n source: stateNode,\n actions: !_target || typeof _target === 'string' ? [] : toArray(_target.actions),\n eventType: null,\n reenter: false,\n target: resolvedTarget ? [resolvedTarget] : [],\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: resolvedTarget ? [`#${resolvedTarget.id}`] : []\n })\n };\n return transition;\n}\nfunction resolveTarget(stateNode, targets) {\n if (targets === 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 return targets.map(target => {\n if (typeof target !== 'string') {\n return target;\n }\n if (isStateId(target)) {\n return stateNode.machine.getStateNodeById(target);\n }\n const isInternalTarget = target[0] === STATE_DELIMITER;\n // If internal target is defined on machine,\n // do not include machine key on target\n if (isInternalTarget && !stateNode.parent) {\n return getStateNodeByPath(stateNode, target.slice(1));\n }\n const resolvedTarget = isInternalTarget ? stateNode.key + target : target;\n if (stateNode.parent) {\n try {\n const targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);\n return targetStateNode;\n } catch (err) {\n throw new Error(`Invalid transition definition for state node '${stateNode.id}':\\n${err.message}`);\n }\n } else {\n throw new Error(`Invalid target: \"${target}\" is not a valid target from the root node. Did you mean \".${target}\"?`);\n }\n });\n}\nfunction resolveHistoryDefaultTransition(stateNode) {\n const normalizedTarget = normalizeTarget(stateNode.config.target);\n if (!normalizedTarget) {\n return stateNode.parent.initial;\n }\n return {\n target: normalizedTarget.map(t => typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t)\n };\n}\nfunction isHistoryNode(stateNode) {\n return stateNode.type === 'history';\n}\nfunction getInitialStateNodesWithTheirAncestors(stateNode) {\n const states = getInitialStateNodes(stateNode);\n for (const initialState of states) {\n for (const ancestor of getProperAncestors(initialState, stateNode)) {\n states.add(ancestor);\n }\n }\n return states;\n}\nfunction getInitialStateNodes(stateNode) {\n const set = new Set();\n function iter(descStateNode) {\n if (set.has(descStateNode)) {\n return;\n }\n set.add(descStateNode);\n if (descStateNode.type === 'compound') {\n iter(descStateNode.initial.target[0]);\n } else if (descStateNode.type === 'parallel') {\n for (const child of getChildren(descStateNode)) {\n iter(child);\n }\n }\n }\n iter(stateNode);\n return set;\n}\n/** Returns the child state node from its relative `stateKey`, or throws. */\nfunction getStateNode(stateNode, stateKey) {\n if (isStateId(stateKey)) {\n return stateNode.machine.getStateNodeById(stateKey);\n }\n if (!stateNode.states) {\n throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);\n }\n const result = stateNode.states[stateKey];\n if (!result) {\n throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);\n }\n return result;\n}\n\n/**\n * Returns the relative state node from the given `statePath`, or throws.\n *\n * @param statePath The string or string array relative path to the state node.\n */\nfunction getStateNodeByPath(stateNode, statePath) {\n if (typeof statePath === 'string' && isStateId(statePath)) {\n try {\n return stateNode.machine.getStateNodeById(statePath);\n } catch (e) {\n // try individual paths\n // throw e;\n }\n }\n const arrayStatePath = toStatePath(statePath).slice();\n let currentStateNode = stateNode;\n while (arrayStatePath.length) {\n const key = arrayStatePath.shift();\n if (!key.length) {\n break;\n }\n currentStateNode = getStateNode(currentStateNode, key);\n }\n return currentStateNode;\n}\n\n/**\n * Returns the state nodes represented by the current state value.\n *\n * @param stateValue The state value or State instance\n */\nfunction getStateNodes(stateNode, stateValue) {\n if (typeof stateValue === 'string') {\n const childStateNode = stateNode.states[stateValue];\n if (!childStateNode) {\n throw new Error(`State '${stateValue}' does not exist on '${stateNode.id}'`);\n }\n return [stateNode, childStateNode];\n }\n const childStateKeys = Object.keys(stateValue);\n const childStateNodes = childStateKeys.map(subStateKey => getStateNode(stateNode, subStateKey)).filter(Boolean);\n return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce((allSubStateNodes, subStateKey) => {\n const subStateNode = getStateNode(stateNode, subStateKey);\n if (!subStateNode) {\n return allSubStateNodes;\n }\n const subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);\n return allSubStateNodes.concat(subStateNodes);\n }, []));\n}\nfunction transitionAtomicNode(stateNode, stateValue, snapshot, event) {\n const childStateNode = getStateNode(stateNode, stateValue);\n const next = childStateNode.next(snapshot, event);\n if (!next || !next.length) {\n return stateNode.next(snapshot, event);\n }\n return next;\n}\nfunction transitionCompoundNode(stateNode, stateValue, snapshot, event) {\n const subStateKeys = Object.keys(stateValue);\n const childStateNode = getStateNode(stateNode, subStateKeys[0]);\n const next = transitionNode(childStateNode, stateValue[subStateKeys[0]], snapshot, event);\n if (!next || !next.length) {\n return stateNode.next(snapshot, event);\n }\n return next;\n}\nfunction transitionParallelNode(stateNode, stateValue, snapshot, event) {\n const allInnerTransitions = [];\n for (const subStateKey of Object.keys(stateValue)) {\n const subStateValue = stateValue[subStateKey];\n if (!subStateValue) {\n continue;\n }\n const subStateNode = getStateNode(stateNode, subStateKey);\n const innerTransitions = transitionNode(subStateNode, subStateValue, snapshot, event);\n if (innerTransitions) {\n allInnerTransitions.push(...innerTransitions);\n }\n }\n if (!allInnerTransitions.length) {\n return stateNode.next(snapshot, event);\n }\n return allInnerTransitions;\n}\nfunction transitionNode(stateNode, stateValue, snapshot, event) {\n // leaf node\n if (typeof stateValue === 'string') {\n return transitionAtomicNode(stateNode, stateValue, snapshot, event);\n }\n\n // compound node\n if (Object.keys(stateValue).length === 1) {\n return transitionCompoundNode(stateNode, stateValue, snapshot, event);\n }\n\n // parallel node\n return transitionParallelNode(stateNode, stateValue, snapshot, event);\n}\nfunction getHistoryNodes(stateNode) {\n return Object.keys(stateNode.states).map(key => stateNode.states[key]).filter(sn => sn.type === 'history');\n}\nfunction isDescendant(childStateNode, parentStateNode) {\n let marker = childStateNode;\n while (marker.parent && marker.parent !== parentStateNode) {\n marker = marker.parent;\n }\n return marker.parent === parentStateNode;\n}\nfunction hasIntersection(s1, s2) {\n const set1 = new Set(s1);\n const set2 = new Set(s2);\n for (const item of set1) {\n if (set2.has(item)) {\n return true;\n }\n }\n for (const item of set2) {\n if (set1.has(item)) {\n return true;\n }\n }\n return false;\n}\nfunction removeConflictingTransitions(enabledTransitions, stateNodeSet, historyValue) {\n const filteredTransitions = new Set();\n for (const t1 of enabledTransitions) {\n let t1Preempted = false;\n const transitionsToRemove = new Set();\n for (const t2 of filteredTransitions) {\n if (hasIntersection(computeExitSet([t1], stateNodeSet, historyValue), computeExitSet([t2], stateNodeSet, historyValue))) {\n if (isDescendant(t1.source, t2.source)) {\n transitionsToRemove.add(t2);\n } else {\n t1Preempted = true;\n break;\n }\n }\n }\n if (!t1Preempted) {\n for (const t3 of transitionsToRemove) {\n filteredTransitions.delete(t3);\n }\n filteredTransitions.add(t1);\n }\n }\n return Array.from(filteredTransitions);\n}\nfunction findLeastCommonAncestor(stateNodes) {\n const [head, ...tail] = stateNodes;\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (tail.every(sn => isDescendant(sn, ancestor))) {\n return ancestor;\n }\n }\n}\nfunction getEffectiveTargetStates(transition, historyValue) {\n if (!transition.target) {\n return [];\n }\n const targets = new Set();\n for (const targetNode of transition.target) {\n if (isHistoryNode(targetNode)) {\n if (historyValue[targetNode.id]) {\n for (const node of historyValue[targetNode.id]) {\n targets.add(node);\n }\n } else {\n for (const node of getEffectiveTargetStates(resolveHistoryDefaultTransition(targetNode), historyValue)) {\n targets.add(node);\n }\n }\n } else {\n targets.add(targetNode);\n }\n }\n return [...targets];\n}\nfunction getTransitionDomain(transition, historyValue) {\n const targetStates = getEffectiveTargetStates(transition, historyValue);\n if (!targetStates) {\n return;\n }\n if (!transition.reenter && targetStates.every(target => target === transition.source || isDescendant(target, transition.source))) {\n return transition.source;\n }\n const lca = findLeastCommonAncestor(targetStates.concat(transition.source));\n if (lca) {\n return lca;\n }\n\n // at this point we know that it's a root transition since LCA couldn't be found\n if (transition.reenter) {\n return;\n }\n return transition.source.machine.root;\n}\nfunction computeExitSet(transitions, stateNodeSet, historyValue) {\n const statesToExit = new Set();\n for (const t of transitions) {\n if (t.target?.length) {\n const domain = getTransitionDomain(t, historyValue);\n if (t.reenter && t.source === domain) {\n statesToExit.add(domain);\n }\n for (const stateNode of stateNodeSet) {\n if (isDescendant(stateNode, domain)) {\n statesToExit.add(stateNode);\n }\n }\n }\n }\n return [...statesToExit];\n}\nfunction areStateNodeCollectionsEqual(prevStateNodes, nextStateNodeSet) {\n if (prevStateNodes.length !== nextStateNodeSet.size) {\n return false;\n }\n for (const node of prevStateNodes) {\n if (!nextStateNodeSet.has(node)) {\n return false;\n }\n }\n return true;\n}\n\n/** https://www.w3.org/TR/scxml/#microstepProcedure */\nfunction microstep(transitions, currentSnapshot, actorScope, event, isInitial, internalQueue) {\n if (!transitions.length) {\n return currentSnapshot;\n }\n const mutStateNodeSet = new Set(currentSnapshot._nodes);\n let historyValue = currentSnapshot.historyValue;\n const filteredTransitions = removeConflictingTransitions(transitions, mutStateNodeSet, historyValue);\n let nextState = currentSnapshot;\n\n // Exit states\n if (!isInitial) {\n [nextState, historyValue] = exitStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, historyValue, internalQueue);\n }\n\n // Execute transition content\n nextState = resolveActionsAndContext(nextState, event, actorScope, filteredTransitions.flatMap(t => t.actions), internalQueue);\n\n // Enter states\n nextState = enterStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial);\n const nextStateNodes = [...mutStateNodeSet];\n if (nextState.status === 'done') {\n nextState = resolveActionsAndContext(nextState, event, actorScope, nextStateNodes.sort((a, b) => b.order - a.order).flatMap(state => state.exit), internalQueue);\n }\n try {\n if (historyValue === currentSnapshot.historyValue && areStateNodeCollectionsEqual(currentSnapshot._nodes, mutStateNodeSet)) {\n return nextState;\n }\n return cloneMachineSnapshot(nextState, {\n _nodes: nextStateNodes,\n historyValue\n });\n } catch (e) {\n // TODO: Refactor this once proper error handling is implemented.\n // See https://github.com/statelyai/rfcs/pull/4\n throw e;\n }\n}\nfunction getMachineOutput(snapshot, event, actorScope, rootNode, rootCompletionNode) {\n if (rootNode.output === undefined) {\n return;\n }\n const doneStateEvent = createDoneStateEvent(rootCompletionNode.id, rootCompletionNode.output !== undefined && rootCompletionNode.parent ? resolveOutput(rootCompletionNode.output, snapshot.context, event, actorScope.self) : undefined);\n return resolveOutput(rootNode.output, snapshot.context, doneStateEvent, actorScope.self);\n}\nfunction enterStates(currentSnapshot, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial) {\n let nextSnapshot = currentSnapshot;\n const statesToEnter = new Set();\n // those are states that were directly targeted or indirectly targeted by the explicit target\n // in other words, those are states for which initial actions should be executed\n // when we target `#deep_child` initial actions of its ancestors shouldn't be executed\n const statesForDefaultEntry = new Set();\n computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);\n\n // In the initial state, the root state node is \"entered\".\n if (isInitial) {\n statesForDefaultEntry.add(currentSnapshot.machine.root);\n }\n const completedNodes = new Set();\n for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {\n mutStateNodeSet.add(stateNodeToEnter);\n const actions = [];\n\n // Add entry actions\n actions.push(...stateNodeToEnter.entry);\n for (const invokeDef of stateNodeToEnter.invoke) {\n actions.push(spawnChild(invokeDef.src, {\n ...invokeDef,\n syncSnapshot: !!invokeDef.onSnapshot\n }));\n }\n if (statesForDefaultEntry.has(stateNodeToEnter)) {\n const initialActions = stateNodeToEnter.initial.actions;\n actions.push(...initialActions);\n }\n nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, actions, internalQueue, stateNodeToEnter.invoke.map(invokeDef => invokeDef.id));\n if (stateNodeToEnter.type === 'final') {\n const parent = stateNodeToEnter.parent;\n let ancestorMarker = parent?.type === 'parallel' ? parent : parent?.parent;\n let rootCompletionNode = ancestorMarker || stateNodeToEnter;\n if (parent?.type === 'compound') {\n internalQueue.push(createDoneStateEvent(parent.id, stateNodeToEnter.output !== undefined ? resolveOutput(stateNodeToEnter.output, nextSnapshot.context, event, actorScope.self) : undefined));\n }\n while (ancestorMarker?.type === 'parallel' && !completedNodes.has(ancestorMarker) && isInFinalState(mutStateNodeSet, ancestorMarker)) {\n completedNodes.add(ancestorMarker);\n internalQueue.push(createDoneStateEvent(ancestorMarker.id));\n rootCompletionNode = ancestorMarker;\n ancestorMarker = ancestorMarker.parent;\n }\n if (ancestorMarker) {\n continue;\n }\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, {\n status: 'done',\n output: getMachineOutput(nextSnapshot, event, actorScope, nextSnapshot.machine.root, rootCompletionNode)\n });\n }\n }\n return nextSnapshot;\n}\nfunction computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {\n for (const t of transitions) {\n const domain = getTransitionDomain(t, historyValue);\n for (const s of t.target || []) {\n if (!isHistoryNode(s) && (\n // if the target is different than the source then it will *definitely* be entered\n t.source !== s ||\n // we know that the domain can't lie within the source\n // if it's different than the source then it's outside of it and it means that the target has to be entered as well\n t.source !== domain ||\n // reentering transitions always enter the target, even if it's the source itself\n t.reenter)) {\n statesToEnter.add(s);\n statesForDefaultEntry.add(s);\n }\n addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);\n }\n const targetStates = getEffectiveTargetStates(t, historyValue);\n for (const s of targetStates) {\n const ancestors = getProperAncestors(s, domain);\n if (domain?.type === 'parallel') {\n ancestors.push(domain);\n }\n addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, !t.source.parent && t.reenter ? undefined : domain);\n }\n }\n}\nfunction addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {\n if (isHistoryNode(stateNode)) {\n if (historyValue[stateNode.id]) {\n const historyStateNodes = historyValue[stateNode.id];\n for (const s of historyStateNodes) {\n statesToEnter.add(s);\n addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);\n }\n for (const s of historyStateNodes) {\n addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);\n }\n } else {\n const historyDefaultTransition = resolveHistoryDefaultTransition(stateNode);\n for (const s of historyDefaultTransition.target) {\n statesToEnter.add(s);\n if (historyDefaultTransition === stateNode.parent?.initial) {\n statesForDefaultEntry.add(stateNode.parent);\n }\n addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);\n }\n for (const s of historyDefaultTransition.target) {\n addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);\n }\n }\n } else {\n if (stateNode.type === 'compound') {\n const [initialState] = stateNode.initial.target;\n if (!isHistoryNode(initialState)) {\n statesToEnter.add(initialState);\n statesForDefaultEntry.add(initialState);\n }\n addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);\n addProperAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);\n } else {\n if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode).filter(sn => !isHistoryNode(sn))) {\n if (![...statesToEnter].some(s => isDescendant(s, child))) {\n if (!isHistoryNode(child)) {\n statesToEnter.add(child);\n statesForDefaultEntry.add(child);\n }\n addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);\n }\n }\n }\n }\n }\n}\nfunction addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, reentrancyDomain) {\n for (const anc of ancestors) {\n if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {\n statesToEnter.add(anc);\n }\n if (anc.type === 'parallel') {\n for (const child of getChildren(anc).filter(sn => !isHistoryNode(sn))) {\n if (![...statesToEnter].some(s => isDescendant(s, child))) {\n statesToEnter.add(child);\n addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);\n }\n }\n }\n }\n}\nfunction addProperAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {\n addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, getProperAncestors(stateNode, toStateNode));\n}\nfunction exitStates(currentSnapshot, event, actorScope, transitions, mutStateNodeSet, historyValue, internalQueue) {\n let nextSnapshot = currentSnapshot;\n const statesToExit = computeExitSet(transitions, mutStateNodeSet, historyValue);\n statesToExit.sort((a, b) => b.order - a.order);\n let changedHistory;\n\n // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates\n for (const exitStateNode of statesToExit) {\n for (const historyNode of getHistoryNodes(exitStateNode)) {\n let predicate;\n if (historyNode.history === 'deep') {\n predicate = sn => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);\n } else {\n predicate = sn => {\n return sn.parent === exitStateNode;\n };\n }\n changedHistory ??= {\n ...historyValue\n };\n changedHistory[historyNode.id] = Array.from(mutStateNodeSet).filter(predicate);\n }\n }\n for (const s of statesToExit) {\n nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, [...s.exit, ...s.invoke.map(def => stopChild(def.id))], internalQueue);\n mutStateNodeSet.delete(s);\n }\n return [nextSnapshot, changedHistory || historyValue];\n}\nlet executingCustomAction = false;\nfunction resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, extra, retries) {\n const {\n machine\n } = currentSnapshot;\n let intermediateSnapshot = currentSnapshot;\n for (const action of actions) {\n const isInline = typeof action === 'function';\n const resolvedAction = isInline ? action :\n // the existing type of `.actions` assumes non-nullable `TExpressionAction`\n // it's fine to cast this here to get a common type and lack of errors in the rest of the code\n // our logic below makes sure that we call those 2 \"variants\" correctly\n machine.implementations.actions[typeof action === 'string' ? action : action.type];\n if (!resolvedAction) {\n continue;\n }\n const actionArgs = {\n context: intermediateSnapshot.context,\n event,\n self: actorScope.self,\n system: actorScope.system\n };\n const actionParams = isInline || typeof action === 'string' ? undefined : 'params' in action ? typeof action.params === 'function' ? action.params({\n context: intermediateSnapshot.context,\n event\n }) : action.params : undefined;\n function executeAction() {\n actorScope.system._sendInspectionEvent({\n type: '@xstate.action',\n actorRef: actorScope.self,\n action: {\n type: typeof action === 'string' ? action : typeof action === 'object' ? action.type : action.name || '(anonymous)',\n params: actionParams\n }\n });\n try {\n executingCustomAction = resolvedAction;\n resolvedAction(actionArgs, actionParams);\n } finally {\n executingCustomAction = false;\n }\n }\n if (!('resolve' in resolvedAction)) {\n if (actorScope.self._processingStatus === ProcessingStatus.Running) {\n executeAction();\n } else {\n actorScope.defer(() => {\n executeAction();\n });\n }\n continue;\n }\n const builtinAction = resolvedAction;\n const [nextState, params, actions] = builtinAction.resolve(actorScope, intermediateSnapshot, actionArgs, actionParams, resolvedAction,\n // this holds all params\n extra);\n intermediateSnapshot = nextState;\n if ('retryResolve' in builtinAction) {\n retries?.push([builtinAction, params]);\n }\n if ('execute' in builtinAction) {\n if (actorScope.self._processingStatus === ProcessingStatus.Running) {\n builtinAction.execute(actorScope, params);\n } else {\n actorScope.defer(builtinAction.execute.bind(null, actorScope, params));\n }\n }\n if (actions) {\n intermediateSnapshot = resolveAndExecuteActionsWithContext(intermediateSnapshot, event, actorScope, actions, extra, retries);\n }\n }\n return intermediateSnapshot;\n}\nfunction resolveActionsAndContext(currentSnapshot, event, actorScope, actions, internalQueue, deferredActorIds) {\n const retries = deferredActorIds ? [] : undefined;\n const nextState = resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, {\n internalQueue,\n deferredActorIds\n }, retries);\n retries?.forEach(([builtinAction, params]) => {\n builtinAction.retryResolve(actorScope, nextState, params);\n });\n return nextState;\n}\nfunction macrostep(snapshot, event, actorScope, internalQueue = []) {\n let nextSnapshot = snapshot;\n const microstates = [];\n function addMicrostate(microstate, event, transitions) {\n actorScope.system._sendInspectionEvent({\n type: '@xstate.microstep',\n actorRef: actorScope.self,\n event,\n snapshot: microstate,\n _transitions: transitions\n });\n microstates.push(microstate);\n }\n\n // Handle stop event\n if (event.type === XSTATE_STOP) {\n nextSnapshot = cloneMachineSnapshot(stopChildren(nextSnapshot, event, actorScope), {\n status: 'stopped'\n });\n addMicrostate(nextSnapshot, event, []);\n return {\n snapshot: nextSnapshot,\n microstates\n };\n }\n let nextEvent = event;\n\n // Assume the state is at rest (no raised events)\n // Determine the next state based on the next microstep\n if (nextEvent.type !== XSTATE_INIT) {\n const currentEvent = nextEvent;\n const isErr = isErrorActorEvent(currentEvent);\n const transitions = selectTransitions(currentEvent, nextSnapshot);\n if (isErr && !transitions.length) {\n // TODO: we should likely only allow transitions selected by very explicit descriptors\n // `*` shouldn't be matched, likely `xstate.error.*` shouldnt be either\n // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too\n nextSnapshot = cloneMachineSnapshot(snapshot, {\n status: 'error',\n error: currentEvent.error\n });\n addMicrostate(nextSnapshot, currentEvent, []);\n return {\n snapshot: nextSnapshot,\n microstates\n };\n }\n nextSnapshot = microstep(transitions, snapshot, actorScope, nextEvent, false,\n // isInitial\n internalQueue);\n addMicrostate(nextSnapshot, currentEvent, transitions);\n }\n let shouldSelectEventlessTransitions = true;\n while (nextSnapshot.status === 'active') {\n let enabledTransitions = shouldSelectEventlessTransitions ? selectEventlessTransitions(nextSnapshot, nextEvent) : [];\n\n // eventless transitions should always be selected after selecting *regular* transitions\n // by assigning `undefined` to `previousState` we ensure that `shouldSelectEventlessTransitions` gets always computed to true in such a case\n const previousState = enabledTransitions.length ? nextSnapshot : undefined;\n if (!enabledTransitions.length) {\n if (!internalQueue.length) {\n break;\n }\n nextEvent = internalQueue.shift();\n enabledTransitions = selectTransitions(nextEvent, nextSnapshot);\n }\n nextSnapshot = microstep(enabledTransitions, nextSnapshot, actorScope, nextEvent, false, internalQueue);\n shouldSelectEventlessTransitions = nextSnapshot !== previousState;\n addMicrostate(nextSnapshot, nextEvent, enabledTransitions);\n }\n if (nextSnapshot.status !== 'active') {\n stopChildren(nextSnapshot, nextEvent, actorScope);\n }\n return {\n snapshot: nextSnapshot,\n microstates\n };\n}\nfunction stopChildren(nextState, event, actorScope) {\n return resolveActionsAndContext(nextState, event, actorScope, Object.values(nextState.children).map(child => stopChild(child)), []);\n}\nfunction selectTransitions(event, nextState) {\n return nextState.machine.getTransitionData(nextState, event);\n}\nfunction selectEventlessTransitions(nextState, event) {\n const enabledTransitionSet = new Set();\n const atomicStates = nextState._nodes.filter(isAtomicStateNode);\n for (const stateNode of atomicStates) {\n loop: for (const s of [stateNode].concat(getProperAncestors(stateNode, undefined))) {\n if (!s.always) {\n continue;\n }\n for (const transition of s.always) {\n if (transition.guard === undefined || evaluateGuard(transition.guard, nextState.context, event, nextState)) {\n enabledTransitionSet.add(transition);\n break loop;\n }\n }\n }\n }\n return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState._nodes), nextState.historyValue);\n}\n\n/**\n * Resolves a partial state value with its full representation in the state\n * node's machine.\n *\n * @param stateValue The partial state value to resolve.\n */\nfunction resolveStateValue(rootNode, stateValue) {\n const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));\n return getStateValue(rootNode, [...allStateNodes]);\n}\n\nfunction isMachineSnapshot(value) {\n return !!value && typeof value === 'object' && 'machine' in value && 'value' in value;\n}\nconst machineSnapshotMatches = function matches(testValue) {\n return matchesState(testValue, this.value);\n};\nconst machineSnapshotHasTag = function hasTag(tag) {\n return this.tags.has(tag);\n};\nconst machineSnapshotCan = function can(event) {\n const transitionData = this.machine.getTransitionData(this, event);\n return !!transitionData?.length &&\n // Check that at least one transition is not forbidden\n transitionData.some(t => t.target !== undefined || t.actions.length);\n};\nconst machineSnapshotToJSON = function toJSON() {\n const {\n _nodes: nodes,\n tags,\n machine,\n getMeta,\n toJSON,\n can,\n hasTag,\n matches,\n ...jsonValues\n } = this;\n return {\n ...jsonValues,\n tags: Array.from(tags)\n };\n};\nconst machineSnapshotGetMeta = function getMeta() {\n return this._nodes.reduce((acc, stateNode) => {\n if (stateNode.meta !== undefined) {\n acc[stateNode.id] = stateNode.meta;\n }\n return acc;\n }, {});\n};\nfunction createMachineSnapshot(config, machine) {\n return {\n status: config.status,\n output: config.output,\n error: config.error,\n machine,\n context: config.context,\n _nodes: config._nodes,\n value: getStateValue(machine.root, config._nodes),\n tags: new Set(config._nodes.flatMap(sn => sn.tags)),\n children: config.children,\n historyValue: config.historyValue || {},\n matches: machineSnapshotMatches,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n toJSON: machineSnapshotToJSON\n };\n}\nfunction cloneMachineSnapshot(snapshot, config = {}) {\n return createMachineSnapshot({\n ...snapshot,\n ...config\n }, snapshot.machine);\n}\nfunction getPersistedSnapshot(snapshot, options) {\n const {\n _nodes: nodes,\n tags,\n machine,\n children,\n context,\n can,\n hasTag,\n matches,\n getMeta,\n toJSON,\n ...jsonValues\n } = snapshot;\n const childrenJson = {};\n for (const id in children) {\n const child = children[id];\n childrenJson[id] = {\n snapshot: child.getPersistedSnapshot(options),\n src: child.src,\n systemId: child._systemId,\n syncSnapshot: child._syncSnapshot\n };\n }\n const persisted = {\n ...jsonValues,\n context: persistContext(context),\n children: childrenJson\n };\n return persisted;\n}\nfunction persistContext(contextPart) {\n let copy;\n for (const key in contextPart) {\n const value = contextPart[key];\n if (value && typeof value === 'object') {\n if ('sessionId' in value && 'send' in value && 'ref' in value) {\n copy ??= Array.isArray(contextPart) ? contextPart.slice() : {\n ...contextPart\n };\n copy[key] = {\n xstate$$type: $$ACTOR_TYPE,\n id: value.id\n };\n } else {\n const result = persistContext(value);\n if (result !== value) {\n copy ??= Array.isArray(contextPart) ? contextPart.slice() : {\n ...contextPart\n };\n copy[key] = result;\n }\n }\n }\n }\n return copy ?? contextPart;\n}\n\nexport { $$ACTOR_TYPE as $, createActor as A, isMachineSnapshot as B, Actor as C, interpret as D, and as E, not as F, or as G, stateIn as H, getAllOwnEventDescriptors as I, matchesState as J, pathToStateValue as K, toObserver as L, cancel as M, NULL_EVENT as N, raise as O, spawnChild as P, stop as Q, stopChild as R, STATE_DELIMITER as S, ProcessingStatus as T, cloneMachineSnapshot as U, XSTATE_ERROR as V, createErrorActorEvent as W, XSTATE_STOP as X, toTransitionConfigArray as a, formatTransition as b, createInvokeId as c, formatInitialTransition as d, evaluateGuard as e, formatTransitions as f, getDelayedTransitions as g, getCandidates as h, getAllStateNodes as i, getStateNodes as j, createMachineSnapshot as k, isInFinalState as l, mapValues as m, macrostep as n, transitionNode as o, resolveActionsAndContext as p, createInitEvent as q, resolveStateValue as r, microstep as s, toArray as t, getInitialStateNodes as u, toStatePath as v, isStateId as w, getStateNodeByPath as x, getPersistedSnapshot as y, resolveReferencedActor as z };\n","import { T as ProcessingStatus, z as resolveReferencedActor, A as createActor, U as cloneMachineSnapshot, V as XSTATE_ERROR, W as createErrorActorEvent, e as evaluateGuard, M as cancel, O as raise, P as spawnChild, R as stopChild } from './State-cdbc7940.esm.js';\n\nfunction createSpawner(actorScope, {\n machine,\n context\n}, event, spawnedChildren) {\n const spawn = (src, options = {}) => {\n const {\n systemId,\n input\n } = options;\n if (typeof src === 'string') {\n const logic = resolveReferencedActor(machine, src);\n if (!logic) {\n throw new Error(`Actor logic '${src}' not implemented in machine '${machine.id}'`);\n }\n const actorRef = createActor(logic, {\n id: options.id,\n parent: actorScope.self,\n syncSnapshot: options.syncSnapshot,\n input: typeof input === 'function' ? input({\n context,\n event,\n self: actorScope.self\n }) : input,\n src,\n systemId\n });\n spawnedChildren[actorRef.id] = actorRef;\n return actorRef;\n } else {\n const actorRef = createActor(src, {\n id: options.id,\n parent: actorScope.self,\n syncSnapshot: options.syncSnapshot,\n input: options.input,\n src,\n systemId\n });\n return actorRef;\n }\n };\n return (src, options) => {\n const actorRef = spawn(src, options); // TODO: fix types\n spawnedChildren[actorRef.id] = actorRef;\n actorScope.defer(() => {\n if (actorRef._processingStatus === ProcessingStatus.Stopped) {\n return;\n }\n actorRef.start();\n });\n return actorRef;\n };\n}\n\nfunction resolveAssign(actorScope, snapshot, actionArgs, actionParams, {\n assignment\n}) {\n if (!snapshot.context) {\n throw new Error('Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.');\n }\n const spawnedChildren = {};\n const assignArgs = {\n context: snapshot.context,\n event: actionArgs.event,\n spawn: createSpawner(actorScope, snapshot, actionArgs.event, spawnedChildren),\n self: actorScope.self,\n system: actorScope.system\n };\n let partialUpdate = {};\n if (typeof assignment === 'function') {\n partialUpdate = assignment(assignArgs, actionParams);\n } else {\n for (const key of Object.keys(assignment)) {\n const propAssignment = assignment[key];\n partialUpdate[key] = typeof propAssignment === 'function' ? propAssignment(assignArgs, actionParams) : propAssignment;\n }\n }\n const updatedContext = Object.assign({}, snapshot.context, partialUpdate);\n return [cloneMachineSnapshot(snapshot, {\n context: updatedContext,\n children: Object.keys(spawnedChildren).length ? {\n ...snapshot.children,\n ...spawnedChildren\n } : snapshot.children\n })];\n}\n/**\n * Updates the current context of the machine.\n *\n * @example\n *\n * ```ts\n * import { createMachine, assign } from 'xstate';\n *\n * const countMachine = createMachine({\n * context: {\n * count: 0,\n * message: ''\n * },\n * on: {\n * inc: {\n * actions: assign({\n * count: ({ context }) => context.count + 1\n * })\n * },\n * updateMessage: {\n * actions: assign(({ context, event }) => {\n * return {\n * message: event.message.trim()\n * };\n * })\n * }\n * }\n * });\n * ```\n *\n * @param assignment An object that represents the partial context to update, or\n * a function that returns an object that represents the partial context to\n * update.\n */\nfunction assign(assignment) {\n function assign(args, params) {\n }\n assign.type = 'xstate.assign';\n assign.assignment = assignment;\n assign.resolve = resolveAssign;\n return assign;\n}\n\nfunction resolveEmit(_, snapshot, args, actionParams, {\n event: eventOrExpr\n}) {\n const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;\n return [snapshot, {\n event: resolvedEvent\n }];\n}\nfunction executeEmit(actorScope, {\n event\n}) {\n actorScope.defer(() => actorScope.emit(event));\n}\n/**\n * Emits an event to event handlers registered on the actor via `actor.on(event,\n * handler)`.\n *\n * @example\n *\n * ```ts\n * import { emit } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * on: {\n * something: {\n * actions: emit({\n * type: 'emitted',\n * some: 'data'\n * })\n * }\n * }\n * // ...\n * });\n *\n * const actor = createActor(machine).start();\n *\n * actor.on('emitted', (event) => {\n * console.log(event);\n * });\n *\n * actor.send({ type: 'something' });\n * // logs:\n * // {\n * // type: 'emitted',\n * // some: 'data'\n * // }\n * ```\n */\nfunction emit( /** The event to emit, or an expression that returns an event to emit. */\neventOrExpr) {\n function emit(args, params) {\n }\n emit.type = 'xstate.emit';\n emit.event = eventOrExpr;\n emit.resolve = resolveEmit;\n emit.execute = executeEmit;\n return emit;\n}\n\n/**\n * @remarks\n * `T | unknown` reduces to `unknown` and that can be problematic when it comes\n * to contextual typing. It especially is a problem when the union has a\n * function member, like here:\n *\n * ```ts\n * declare function test(\n * cbOrVal: ((arg: number) => unknown) | unknown\n * ): void;\n * test((arg) => {}); // oops, implicit any\n * ```\n *\n * This type can be used to avoid this problem. This union represents the same\n * value space as `unknown`.\n */\n\n// https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887\n\n// @TODO: Replace with native `NoInfer` when TS issue gets fixed:\n// https://github.com/microsoft/TypeScript/pull/57673\n/** @deprecated Use the built-in `NoInfer` type instead */\n/** The full definition of an event, with a string `type`. */\n/**\n * The string or object representing the state value relative to the parent\n * state node.\n *\n * @remarks\n * - For a child atomic state node, this is a string, e.g., `\"pending\"`.\n * - For complex state nodes, this is an object, e.g., `{ success:\n * \"someChildState\" }`.\n */\n// TODO: remove once TS fixes this type-widening issue\n/** @deprecated Use `AnyMachineSnapshot` instead */\n// TODO: possibly refactor this somehow, use even a simpler type, and maybe even make `machine.options` private or something\n/** @ignore */\nlet SpecialTargets = /*#__PURE__*/function (SpecialTargets) {\n SpecialTargets[\"Parent\"] = \"#_parent\";\n SpecialTargets[\"Internal\"] = \"#_internal\";\n return SpecialTargets;\n}({});\n\n/** @deprecated Use `AnyActor` instead. */\n\n// Based on RxJS types\n\n// TODO: in v6, this should only accept AnyActorLogic, like ActorRefFromLogic\n\n/** @deprecated Use `Actor` instead. */\n\n/**\n * Represents logic which can be used by an actor.\n *\n * @template TSnapshot - The type of the snapshot.\n * @template TEvent - The type of the event object.\n * @template TInput - The type of the input.\n * @template TSystem - The type of the actor system.\n */\n\n/** @deprecated */\n\nfunction resolveSendTo(actorScope, snapshot, args, actionParams, {\n to,\n event: eventOrExpr,\n id,\n delay\n}, extra) {\n const delaysMap = snapshot.machine.implementations.delays;\n if (typeof eventOrExpr === 'string') {\n throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: \"${eventOrExpr}\" }) instead`);\n }\n const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;\n let resolvedDelay;\n if (typeof delay === 'string') {\n const configDelay = delaysMap && delaysMap[delay];\n resolvedDelay = typeof configDelay === 'function' ? configDelay(args, actionParams) : configDelay;\n } else {\n resolvedDelay = typeof delay === 'function' ? delay(args, actionParams) : delay;\n }\n const resolvedTarget = typeof to === 'function' ? to(args, actionParams) : to;\n let targetActorRef;\n if (typeof resolvedTarget === 'string') {\n if (resolvedTarget === SpecialTargets.Parent) {\n targetActorRef = actorScope.self._parent;\n } else if (resolvedTarget === SpecialTargets.Internal) {\n targetActorRef = actorScope.self;\n } else if (resolvedTarget.startsWith('#_')) {\n // SCXML compatibility: https://www.w3.org/TR/scxml/#SCXMLEventProcessor\n // #_invokeid. If the target is the special term '#_invokeid', where invokeid is the invokeid of an SCXML session that the sending session has created by , the Processor must add the event to the external queue of that session.\n targetActorRef = snapshot.children[resolvedTarget.slice(2)];\n } else {\n targetActorRef = extra.deferredActorIds?.includes(resolvedTarget) ? resolvedTarget : snapshot.children[resolvedTarget];\n }\n if (!targetActorRef) {\n throw new Error(`Unable to send event to actor '${resolvedTarget}' from machine '${snapshot.machine.id}'.`);\n }\n } else {\n targetActorRef = resolvedTarget || actorScope.self;\n }\n return [snapshot, {\n to: targetActorRef,\n event: resolvedEvent,\n id,\n delay: resolvedDelay\n }];\n}\nfunction retryResolveSendTo(_, snapshot, params) {\n if (typeof params.to === 'string') {\n params.to = snapshot.children[params.to];\n }\n}\nfunction executeSendTo(actorScope, params) {\n // this forms an outgoing events queue\n // thanks to that the recipient actors are able to read the *updated* snapshot value of the sender\n actorScope.defer(() => {\n const {\n to,\n event,\n delay,\n id\n } = params;\n if (typeof delay === 'number') {\n actorScope.system.scheduler.schedule(actorScope.self, to, event, delay, id);\n return;\n }\n actorScope.system._relay(actorScope.self,\n // at this point, in a deferred task, it should already be mutated by retryResolveSendTo\n // if it initially started as a string\n to, event.type === XSTATE_ERROR ? createErrorActorEvent(actorScope.self.id, event.data) : event);\n });\n}\n/**\n * Sends an event to an actor.\n *\n * @param actor The `ActorRef` to send the event to.\n * @param event The event to send, or an expression that evaluates to the event\n * to send\n * @param options Send action options\n *\n * - `id` - The unique send event identifier (used with `cancel()`).\n * - `delay` - The number of milliseconds to delay the sending of the event.\n */\nfunction sendTo(to, eventOrExpr, options) {\n function sendTo(args, params) {\n }\n sendTo.type = 'xsnapshot.sendTo';\n sendTo.to = to;\n sendTo.event = eventOrExpr;\n sendTo.id = options?.id;\n sendTo.delay = options?.delay;\n sendTo.resolve = resolveSendTo;\n sendTo.retryResolve = retryResolveSendTo;\n sendTo.execute = executeSendTo;\n return sendTo;\n}\n\n/**\n * Sends an event to this machine's parent.\n *\n * @param event The event to send to the parent machine.\n * @param options Options to pass into the send event.\n */\nfunction sendParent(event, options) {\n return sendTo(SpecialTargets.Parent, event, options);\n}\n/**\n * Forwards (sends) an event to the `target` actor.\n *\n * @param target The target actor to forward the event to.\n * @param options Options to pass into the send action creator.\n */\nfunction forwardTo(target, options) {\n return sendTo(target, ({\n event\n }) => event, options);\n}\n\nfunction resolveEnqueueActions(actorScope, snapshot, args, actionParams, {\n collect\n}) {\n const actions = [];\n const enqueue = function enqueue(action) {\n actions.push(action);\n };\n enqueue.assign = (...args) => {\n actions.push(assign(...args));\n };\n enqueue.cancel = (...args) => {\n actions.push(cancel(...args));\n };\n enqueue.raise = (...args) => {\n // for some reason it fails to infer `TDelay` from `...args` here and picks its default (`never`)\n // then it fails to typecheck that because `...args` use `string` in place of `TDelay`\n actions.push(raise(...args));\n };\n enqueue.sendTo = (...args) => {\n // for some reason it fails to infer `TDelay` from `...args` here and picks its default (`never`)\n // then it fails to typecheck that because `...args` use `string` in place of `TDelay\n actions.push(sendTo(...args));\n };\n enqueue.sendParent = (...args) => {\n actions.push(sendParent(...args));\n };\n enqueue.spawnChild = (...args) => {\n actions.push(spawnChild(...args));\n };\n enqueue.stopChild = (...args) => {\n actions.push(stopChild(...args));\n };\n enqueue.emit = (...args) => {\n actions.push(emit(...args));\n };\n collect({\n context: args.context,\n event: args.event,\n enqueue,\n check: guard => evaluateGuard(guard, snapshot.context, args.event, snapshot),\n self: actorScope.self,\n system: actorScope.system\n }, actionParams);\n return [snapshot, undefined, actions];\n}\n/**\n * Creates an action object that will execute actions that are queued by the\n * `enqueue(action)` function.\n *\n * @example\n *\n * ```ts\n * import { createMachine, enqueueActions } from 'xstate';\n *\n * const machine = createMachine({\n * entry: enqueueActions(({ enqueue, check }) => {\n * enqueue.assign({ count: 0 });\n *\n * if (check('someGuard')) {\n * enqueue.assign({ count: 1 });\n * }\n *\n * enqueue('someAction');\n * })\n * });\n * ```\n */\nfunction enqueueActions(collect) {\n function enqueueActions(args, params) {\n }\n enqueueActions.type = 'xstate.enqueueActions';\n enqueueActions.collect = collect;\n enqueueActions.resolve = resolveEnqueueActions;\n return enqueueActions;\n}\n\nfunction resolveLog(_, snapshot, actionArgs, actionParams, {\n value,\n label\n}) {\n return [snapshot, {\n value: typeof value === 'function' ? value(actionArgs, actionParams) : value,\n label\n }];\n}\nfunction executeLog({\n logger\n}, {\n value,\n label\n}) {\n if (label) {\n logger(label, value);\n } else {\n logger(value);\n }\n}\n/**\n * @param expr The expression function to evaluate which will be logged. Takes\n * in 2 arguments:\n *\n * - `ctx` - the current state context\n * - `event` - the event that caused this action to be executed.\n *\n * @param label The label to give to the logged expression.\n */\nfunction log(value = ({\n context,\n event\n}) => ({\n context,\n event\n}), label) {\n function log(args, params) {\n }\n log.type = 'xstate.log';\n log.value = value;\n log.label = label;\n log.resolve = resolveLog;\n log.execute = executeLog;\n return log;\n}\n\nexport { SpecialTargets as S, assign as a, enqueueActions as b, sendTo as c, emit as e, forwardTo as f, log as l, sendParent as s };\n","import { X as XSTATE_STOP, A as createActor } from '../../dist/State-cdbc7940.esm.js';\nimport '../../dev/dist/xstate-dev.esm.js';\n\n/**\n * Represents an actor created by `fromTransition`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import {\n * fromTransition,\n * createActor,\n * type AnyActorSystem\n * } from 'xstate';\n *\n * //* The actor's stored context.\n * type Context = {\n * // The current count.\n * count: number;\n * // The amount to increase `count` by.\n * step: number;\n * };\n * // The events the actor receives.\n * type Event = { type: 'increment' };\n * // The actor's input.\n * type Input = { step?: number };\n *\n * // Actor logic that increments `count` by `step` when it receives an event of\n * // type `increment`.\n * const logic = fromTransition(\n * (state, event, actorScope) => {\n * actorScope.self;\n * // ^? TransitionActorRef\n *\n * if (event.type === 'increment') {\n * return {\n * ...state,\n * count: state.count + state.step\n * };\n * }\n * return state;\n * },\n * ({ input, self }) => {\n * self;\n * // ^? TransitionActorRef\n *\n * return {\n * count: 0,\n * step: input.step ?? 1\n * };\n * }\n * );\n *\n * const actor = createActor(logic, { input: { step: 10 } });\n * // ^? TransitionActorRef\n * ```\n *\n * @see {@link fromTransition}\n */\n\n/**\n * Returns actor logic given a transition function and its initial state.\n *\n * A “transition function” is a function that takes the current `state` and\n * received `event` object as arguments, and returns the next state, similar to\n * a reducer.\n *\n * Actors created from transition logic (“transition actors”) can:\n *\n * - Receive events\n * - Emit snapshots of its state\n *\n * The transition function’s `state` is used as its transition actor’s\n * `context`.\n *\n * Note that the \"state\" for a transition function is provided by the initial\n * state argument, and is not the same as the State object of an actor or a\n * state within a machine configuration.\n *\n * @example\n *\n * ```ts\n * const transitionLogic = fromTransition(\n * (state, event) => {\n * if (event.type === 'increment') {\n * return {\n * ...state,\n * count: state.count + 1\n * };\n * }\n * return state;\n * },\n * { count: 0 }\n * );\n *\n * const transitionActor = createActor(transitionLogic);\n * transitionActor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * transitionActor.start();\n * // => {\n * // status: 'active',\n * // context: { count: 0 },\n * // ...\n * // }\n *\n * transitionActor.send({ type: 'increment' });\n * // => {\n * // status: 'active',\n * // context: { count: 1 },\n * // ...\n * // }\n * ```\n *\n * @param transition The transition function used to describe the transition\n * logic. It should return the next state given the current state and event.\n * It receives the following arguments:\n *\n * - `state` - the current state.\n * - `event` - the received event.\n * - `actorScope` - the actor scope object, with properties like `self` and\n * `system`.\n *\n * @param initialContext The initial state of the transition function, either an\n * object representing the state, or a function which returns a state object.\n * If a function, it will receive as its only argument an object with the\n * following properties:\n *\n * - `input` - the `input` provided to its parent transition actor.\n * - `self` - a reference to its parent transition actor.\n *\n * @returns Actor logic\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nfunction fromTransition(transition, initialContext) {\n return {\n config: transition,\n transition: (snapshot, event, actorScope) => {\n return {\n ...snapshot,\n context: transition(snapshot.context, event, actorScope)\n };\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: typeof initialContext === 'function' ? initialContext({\n input\n }) : initialContext\n };\n },\n getPersistedSnapshot: snapshot => snapshot,\n restoreSnapshot: snapshot => snapshot\n };\n}\n\nconst instanceStates = /* #__PURE__ */new WeakMap();\n\n/**\n * Represents an actor created by `fromCallback`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { fromCallback, createActor } from 'xstate';\n *\n * // The events the actor receives.\n * type Event = { type: 'someEvent' };\n * // The actor's input.\n * type Input = { name: string };\n *\n * // Actor logic that logs whenever it receives an event of type `someEvent`.\n * const logic = fromCallback(({ self, input, receive }) => {\n * self;\n * // ^? CallbackActorRef\n *\n * receive((event) => {\n * if (event.type === 'someEvent') {\n * console.log(`${input.name}: received \"someEvent\" event`);\n * // logs 'myActor: received \"someEvent\" event'\n * }\n * });\n * });\n *\n * const actor = createActor(logic, { input: { name: 'myActor' } });\n * // ^? CallbackActorRef\n * ```\n *\n * @see {@link fromCallback}\n */\n\n/**\n * An actor logic creator which returns callback logic as defined by a callback\n * function.\n *\n * @remarks\n * Useful for subscription-based or other free-form logic that can send events\n * back to the parent actor.\n *\n * Actors created from callback logic (“callback actors”) can:\n *\n * - Receive events via the `receive` function\n * - Send events to the parent actor via the `sendBack` function\n *\n * Callback actors are a bit different from other actors in that they:\n *\n * - Do not work with `onDone`\n * - Do not produce a snapshot using `.getSnapshot()`\n * - Do not emit values when used with `.subscribe()`\n * - Can not be stopped with `.stop()`\n *\n * @example\n *\n * ```typescript\n * const callbackLogic = fromCallback(({ sendBack, receive }) => {\n * let lockStatus = 'unlocked';\n *\n * const handler = (event) => {\n * if (lockStatus === 'locked') {\n * return;\n * }\n * sendBack(event);\n * };\n *\n * receive((event) => {\n * if (event.type === 'lock') {\n * lockStatus = 'locked';\n * } else if (event.type === 'unlock') {\n * lockStatus = 'unlocked';\n * }\n * });\n *\n * document.body.addEventListener('click', handler);\n *\n * return () => {\n * document.body.removeEventListener('click', handler);\n * };\n * });\n * ```\n *\n * @param invokeCallback - The callback function used to describe the callback\n * logic The callback function is passed an object with the following\n * properties:\n *\n * - `receive` - A function that can send events back to the parent actor; the\n * listener is then called whenever events are received by the callback\n * actor\n * - `sendBack` - A function that can send events back to the parent actor\n * - `input` - Data that was provided to the callback actor\n * - `self` - The parent actor of the callback actor\n * - `system` - The actor system to which the callback actor belongs The callback\n * function can (optionally) return a cleanup function, which is called\n * when the actor is stopped.\n *\n * @returns Callback logic\n * @see {@link InvokeCallback} for more information about the callback function and its object argument\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nfunction fromCallback(invokeCallback) {\n const logic = {\n config: invokeCallback,\n start: (state, actorScope) => {\n const {\n self,\n system,\n emit\n } = actorScope;\n const callbackState = {\n receivers: undefined,\n dispose: undefined\n };\n instanceStates.set(self, callbackState);\n callbackState.dispose = invokeCallback({\n input: state.input,\n system,\n self,\n sendBack: event => {\n if (self.getSnapshot().status === 'stopped') {\n return;\n }\n if (self._parent) {\n system._relay(self, self._parent, event);\n }\n },\n receive: listener => {\n callbackState.receivers ??= new Set();\n callbackState.receivers.add(listener);\n },\n emit\n });\n },\n transition: (state, event, actorScope) => {\n const callbackState = instanceStates.get(actorScope.self);\n if (event.type === XSTATE_STOP) {\n state = {\n ...state,\n status: 'stopped',\n error: undefined\n };\n callbackState.dispose?.();\n return state;\n }\n callbackState.receivers?.forEach(receiver => receiver(event));\n return state;\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n };\n },\n getPersistedSnapshot: snapshot => snapshot,\n restoreSnapshot: snapshot => snapshot\n };\n return logic;\n}\n\nconst XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';\nconst XSTATE_OBSERVABLE_ERROR = 'xstate.observable.error';\nconst XSTATE_OBSERVABLE_COMPLETE = 'xstate.observable.complete';\n\n/**\n * Represents an actor created by `fromObservable` or `fromEventObservable`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { fromObservable, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * // The type of the value observed by the actor's logic.\n * type Context = number;\n * // The actor's input.\n * type Input = { period?: number };\n *\n * // Actor logic that observes a number incremented every `input.period`\n * // milliseconds (default: 1_000).\n * const logic = fromObservable(({ input, self }) => {\n * self;\n * // ^? ObservableActorRef\n *\n * return interval(input.period ?? 1_000);\n * });\n *\n * const actor = createActor(logic, { input: { period: 2_000 } });\n * // ^? ObservableActorRef\n * ```\n *\n * @see {@link fromObservable}\n * @see {@link fromEventObservable}\n */\n\n/**\n * Observable actor logic is described by an observable stream of values. Actors\n * created from observable logic (“observable actors”) can:\n *\n * - Emit snapshots of the observable’s emitted value\n *\n * The observable’s emitted value is used as its observable actor’s `context`.\n *\n * Sending events to observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import { fromObservable, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * const logic = fromObservable((obj) => interval(1000));\n *\n * const actor = createActor(logic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot.context);\n * });\n *\n * actor.start();\n * // At every second:\n * // Logs 0\n * // Logs 1\n * // Logs 2\n * // ...\n * ```\n *\n * @param observableCreator A function that creates an observable. It receives\n * one argument, an object with the following properties:\n *\n * - `input` - Data that was provided to the observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the observable actor belongs\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS\n * Observable, although RxJS is not required to create them.\n * @see {@link https://rxjs.dev} for documentation on RxJS Observable and observable creators.\n * @see {@link Subscribable} interface in XState, which is based on and compatible with RxJS Observable.\n */\nfunction fromObservable(observableCreator) {\n // TODO: add event types\n const logic = {\n config: observableCreator,\n transition: (snapshot, event) => {\n if (snapshot.status !== 'active') {\n return snapshot;\n }\n switch (event.type) {\n case XSTATE_OBSERVABLE_NEXT:\n {\n const newSnapshot = {\n ...snapshot,\n context: event.data\n };\n return newSnapshot;\n }\n case XSTATE_OBSERVABLE_ERROR:\n return {\n ...snapshot,\n status: 'error',\n error: event.data,\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_OBSERVABLE_COMPLETE:\n return {\n ...snapshot,\n status: 'done',\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_STOP:\n snapshot._subscription.unsubscribe();\n return {\n ...snapshot,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n };\n default:\n return snapshot;\n }\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n };\n },\n start: (state, {\n self,\n system,\n emit\n }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n state._subscription = observableCreator({\n input: state.input,\n system,\n self,\n emit\n }).subscribe({\n next: value => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_NEXT,\n data: value\n });\n },\n error: err => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_COMPLETE\n });\n }\n });\n },\n getPersistedSnapshot: ({\n _subscription,\n ...state\n }) => state,\n restoreSnapshot: state => ({\n ...state,\n _subscription: undefined\n })\n };\n return logic;\n}\n\n/**\n * Creates event observable logic that listens to an observable that delivers\n * event objects.\n *\n * Event observable actor logic is described by an observable stream of\n * {@link https://stately.ai/docs/transitions#event-objects | event objects}.\n * Actors created from event observable logic (“event observable actors”) can:\n *\n * - Implicitly send events to its parent actor\n * - Emit snapshots of its emitted event objects\n *\n * Sending events to event observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import {\n * fromEventObservable,\n * Subscribable,\n * EventObject,\n * createMachine,\n * createActor\n * } from 'xstate';\n * import { fromEvent } from 'rxjs';\n *\n * const mouseClickLogic = fromEventObservable(\n * () => fromEvent(document.body, 'click') as Subscribable\n * );\n *\n * const canvasMachine = createMachine({\n * invoke: {\n * // Will send mouse `click` events to the canvas actor\n * src: mouseClickLogic\n * }\n * });\n *\n * const canvasActor = createActor(canvasMachine);\n * canvasActor.start();\n * ```\n *\n * @param lazyObservable A function that creates an observable that delivers\n * event objects. It receives one argument, an object with the following\n * properties:\n *\n * - `input` - Data that was provided to the event observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the event observable actor belongs.\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS\n * Observable, although RxJS is not required to create them.\n */\nfunction fromEventObservable(lazyObservable) {\n // TODO: event types\n const logic = {\n config: lazyObservable,\n transition: (state, event) => {\n if (state.status !== 'active') {\n return state;\n }\n switch (event.type) {\n case XSTATE_OBSERVABLE_ERROR:\n return {\n ...state,\n status: 'error',\n error: event.data,\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_OBSERVABLE_COMPLETE:\n return {\n ...state,\n status: 'done',\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_STOP:\n state._subscription.unsubscribe();\n return {\n ...state,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n };\n default:\n return state;\n }\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n };\n },\n start: (state, {\n self,\n system,\n emit\n }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n state._subscription = lazyObservable({\n input: state.input,\n system,\n self,\n emit\n }).subscribe({\n next: value => {\n if (self._parent) {\n system._relay(self, self._parent, value);\n }\n },\n error: err => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_COMPLETE\n });\n }\n });\n },\n getPersistedSnapshot: ({\n _subscription,\n ...snapshot\n }) => snapshot,\n restoreSnapshot: snapshot => ({\n ...snapshot,\n _subscription: undefined\n })\n };\n return logic;\n}\n\nconst XSTATE_PROMISE_RESOLVE = 'xstate.promise.resolve';\nconst XSTATE_PROMISE_REJECT = 'xstate.promise.reject';\n\n/**\n * Represents an actor created by `fromPromise`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { fromPromise, createActor } from 'xstate';\n *\n * // The actor's resolved output\n * type Output = string;\n * // The actor's input.\n * type Input = { message: string };\n *\n * // Actor logic that fetches the url of an image of a cat saying `input.message`.\n * const logic = fromPromise(async ({ input, self }) => {\n * self;\n * // ^? PromiseActorRef\n *\n * const data = await fetch(\n * `https://cataas.com/cat/says/${input.message}`\n * );\n * const url = await data.json();\n * return url;\n * });\n *\n * const actor = createActor(logic, { input: { message: 'hello world' } });\n * // ^? PromiseActorRef\n * ```\n *\n * @see {@link fromPromise}\n */\n\nconst controllerMap = new WeakMap();\n\n/**\n * An actor logic creator which returns promise logic as defined by an async\n * process that resolves or rejects after some time.\n *\n * Actors created from promise actor logic (“promise actors”) can:\n *\n * - Emit the resolved value of the promise\n * - Output the resolved value of the promise\n *\n * Sending events to promise actors will have no effect.\n *\n * @example\n *\n * ```ts\n * const promiseLogic = fromPromise(async () => {\n * const result = await fetch('https://example.com/...').then((data) =>\n * data.json()\n * );\n *\n * return result;\n * });\n *\n * const promiseActor = createActor(promiseLogic);\n * promiseActor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * promiseActor.start();\n * // => {\n * // output: undefined,\n * // status: 'active'\n * // ...\n * // }\n *\n * // After promise resolves\n * // => {\n * // output: { ... },\n * // status: 'done',\n * // ...\n * // }\n * ```\n *\n * @param promiseCreator A function which returns a Promise, and accepts an\n * object with the following properties:\n *\n * - `input` - Data that was provided to the promise actor\n * - `self` - The parent actor of the promise actor\n * - `system` - The actor system to which the promise actor belongs\n *\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nfunction fromPromise(promiseCreator) {\n const logic = {\n config: promiseCreator,\n transition: (state, event, scope) => {\n if (state.status !== 'active') {\n return state;\n }\n switch (event.type) {\n case XSTATE_PROMISE_RESOLVE:\n {\n const resolvedValue = event.data;\n return {\n ...state,\n status: 'done',\n output: resolvedValue,\n input: undefined\n };\n }\n case XSTATE_PROMISE_REJECT:\n return {\n ...state,\n status: 'error',\n error: event.data,\n input: undefined\n };\n case XSTATE_STOP:\n {\n controllerMap.get(scope.self)?.abort();\n return {\n ...state,\n status: 'stopped',\n input: undefined\n };\n }\n default:\n return state;\n }\n },\n start: (state, {\n self,\n system,\n emit\n }) => {\n // TODO: determine how to allow customizing this so that promises\n // can be restarted if necessary\n if (state.status !== 'active') {\n return;\n }\n const controller = new AbortController();\n controllerMap.set(self, controller);\n const resolvedPromise = Promise.resolve(promiseCreator({\n input: state.input,\n system,\n self,\n signal: controller.signal,\n emit\n }));\n resolvedPromise.then(response => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n controllerMap.delete(self);\n system._relay(self, self, {\n type: XSTATE_PROMISE_RESOLVE,\n data: response\n });\n }, errorData => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n controllerMap.delete(self);\n system._relay(self, self, {\n type: XSTATE_PROMISE_REJECT,\n data: errorData\n });\n });\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n };\n },\n getPersistedSnapshot: snapshot => snapshot,\n restoreSnapshot: snapshot => snapshot\n };\n return logic;\n}\n\nconst emptyLogic = fromTransition(_ => undefined, undefined);\nfunction createEmptyActor() {\n return createActor(emptyLogic);\n}\n\nexport { createEmptyActor, fromCallback, fromEventObservable, fromObservable, fromPromise, fromTransition };\n","import { S as STATE_DELIMITER, m as mapValues, t as toArray, f as formatTransitions, a as toTransitionConfigArray, b as formatTransition, N as NULL_EVENT, e as evaluateGuard, c as createInvokeId, g as getDelayedTransitions, d as formatInitialTransition, h as getCandidates, r as resolveStateValue, i as getAllStateNodes, j as getStateNodes, k as createMachineSnapshot, l as isInFinalState, n as macrostep, o as transitionNode, p as resolveActionsAndContext, q as createInitEvent, s as microstep, u as getInitialStateNodes, v as toStatePath, w as isStateId, x as getStateNodeByPath, y as getPersistedSnapshot, z as resolveReferencedActor, A as createActor, $ as $$ACTOR_TYPE } from './State-cdbc7940.esm.js';\nexport { C as Actor, I as __unsafe_getAllOwnEventDescriptors, E as and, M as cancel, A as createActor, j as getStateNodes, D as interpret, B as isMachineSnapshot, J as matchesState, F as not, G as or, K as pathToStateValue, O as raise, P as spawnChild, H as stateIn, Q as stop, R as stopChild, L as toObserver } from './State-cdbc7940.esm.js';\nimport { a as assign } from './log-54d038f7.esm.js';\nexport { S as SpecialTargets, a as assign, e as emit, b as enqueueActions, f as forwardTo, l as log, s as sendParent, c as sendTo } from './log-54d038f7.esm.js';\nexport { createEmptyActor, fromCallback, fromEventObservable, fromObservable, fromPromise, fromTransition } from '../actors/dist/xstate-actors.esm.js';\nimport '../dev/dist/xstate-dev.esm.js';\n\nclass SimulatedClock {\n constructor() {\n this.timeouts = new Map();\n this._now = 0;\n this._id = 0;\n this._flushing = false;\n this._flushingInvalidated = false;\n }\n now() {\n return this._now;\n }\n getId() {\n return this._id++;\n }\n setTimeout(fn, timeout) {\n this._flushingInvalidated = this._flushing;\n const id = this.getId();\n this.timeouts.set(id, {\n start: this.now(),\n timeout,\n fn\n });\n return id;\n }\n clearTimeout(id) {\n this._flushingInvalidated = this._flushing;\n this.timeouts.delete(id);\n }\n set(time) {\n if (this._now > time) {\n throw new Error('Unable to travel back in time');\n }\n this._now = time;\n this.flushTimeouts();\n }\n flushTimeouts() {\n if (this._flushing) {\n this._flushingInvalidated = true;\n return;\n }\n this._flushing = true;\n const sorted = [...this.timeouts].sort(([_idA, timeoutA], [_idB, timeoutB]) => {\n const endA = timeoutA.start + timeoutA.timeout;\n const endB = timeoutB.start + timeoutB.timeout;\n return endB > endA ? -1 : 1;\n });\n for (const [id, timeout] of sorted) {\n if (this._flushingInvalidated) {\n this._flushingInvalidated = false;\n this._flushing = false;\n this.flushTimeouts();\n return;\n }\n if (this.now() - timeout.start >= timeout.timeout) {\n this.timeouts.delete(id);\n timeout.fn.call(null);\n }\n }\n this._flushing = false;\n }\n increment(ms) {\n this._now += ms;\n this.flushTimeouts();\n }\n}\n\nconst cache = new WeakMap();\nfunction memo(object, key, fn) {\n let memoizedData = cache.get(object);\n if (!memoizedData) {\n memoizedData = {\n [key]: fn()\n };\n cache.set(object, memoizedData);\n } else if (!(key in memoizedData)) {\n memoizedData[key] = fn();\n }\n return memoizedData[key];\n}\n\nconst EMPTY_OBJECT = {};\nconst toSerializableAction = action => {\n if (typeof action === 'string') {\n return {\n type: action\n };\n }\n if (typeof action === 'function') {\n if ('resolve' in action) {\n return {\n type: action.type\n };\n }\n return {\n type: action.name\n };\n }\n return action;\n};\nclass StateNode {\n constructor( /** The raw config used to create the machine. */\n config, options) {\n this.config = config;\n /**\n * The relative key of the state node, which represents its location in the\n * overall state value.\n */\n this.key = void 0;\n /** The unique ID of the state node. */\n this.id = void 0;\n /**\n * The type of this state node:\n *\n * - `'atomic'` - no child state nodes\n * - `'compound'` - nested child state nodes (XOR)\n * - `'parallel'` - orthogonal nested child state nodes (AND)\n * - `'history'` - history state node\n * - `'final'` - final state node\n */\n this.type = void 0;\n /** The string path from the root machine node to this node. */\n this.path = void 0;\n /** The child state nodes. */\n this.states = void 0;\n /**\n * The type of history on this state node. Can be:\n *\n * - `'shallow'` - recalls only top-level historical state value\n * - `'deep'` - recalls historical state value at all levels\n */\n this.history = void 0;\n /** The action(s) to be executed upon entering the state node. */\n this.entry = void 0;\n /** The action(s) to be executed upon exiting the state node. */\n this.exit = void 0;\n /** The parent state node. */\n this.parent = void 0;\n /** The root machine node. */\n this.machine = void 0;\n /**\n * The meta data associated with this state node, which will be returned in\n * State instances.\n */\n this.meta = void 0;\n /**\n * The output data sent with the \"xstate.done.state._id_\" event if this is a\n * final state node.\n */\n this.output = void 0;\n /**\n * The order this state node appears. Corresponds to the implicit document\n * order.\n */\n this.order = -1;\n this.description = void 0;\n this.tags = [];\n this.transitions = void 0;\n this.always = void 0;\n this.parent = options._parent;\n this.key = options._key;\n this.machine = options._machine;\n this.path = this.parent ? this.parent.path.concat(this.key) : [];\n this.id = this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);\n this.type = this.config.type || (this.config.states && Object.keys(this.config.states).length ? 'compound' : this.config.history ? 'history' : 'atomic');\n this.description = this.config.description;\n this.order = this.machine.idMap.size;\n this.machine.idMap.set(this.id, this);\n this.states = this.config.states ? mapValues(this.config.states, (stateConfig, key) => {\n const stateNode = new StateNode(stateConfig, {\n _parent: this,\n _key: key,\n _machine: this.machine\n });\n return stateNode;\n }) : EMPTY_OBJECT;\n if (this.type === 'compound' && !this.config.initial) {\n throw new Error(`No initial state specified for compound state node \"#${this.id}\". Try adding { initial: \"${Object.keys(this.states)[0]}\" } to the state config.`);\n }\n\n // History config\n this.history = this.config.history === true ? 'shallow' : this.config.history || false;\n this.entry = toArray(this.config.entry).slice();\n this.exit = toArray(this.config.exit).slice();\n this.meta = this.config.meta;\n this.output = this.type === 'final' || !this.parent ? this.config.output : undefined;\n this.tags = toArray(config.tags).slice();\n }\n\n /** @internal */\n _initialize() {\n this.transitions = formatTransitions(this);\n if (this.config.always) {\n this.always = toTransitionConfigArray(this.config.always).map(t => formatTransition(this, NULL_EVENT, t));\n }\n Object.keys(this.states).forEach(key => {\n this.states[key]._initialize();\n });\n }\n\n /** The well-structured state node definition. */\n get definition() {\n return {\n id: this.id,\n key: this.key,\n version: this.machine.version,\n type: this.type,\n initial: this.initial ? {\n target: this.initial.target,\n source: this,\n actions: this.initial.actions.map(toSerializableAction),\n eventType: null,\n reenter: false,\n toJSON: () => ({\n target: this.initial.target.map(t => `#${t.id}`),\n source: `#${this.id}`,\n actions: this.initial.actions.map(toSerializableAction),\n eventType: null\n })\n } : undefined,\n history: this.history,\n states: mapValues(this.states, state => {\n return state.definition;\n }),\n on: this.on,\n transitions: [...this.transitions.values()].flat().map(t => ({\n ...t,\n actions: t.actions.map(toSerializableAction)\n })),\n entry: this.entry.map(toSerializableAction),\n exit: this.exit.map(toSerializableAction),\n meta: this.meta,\n order: this.order || -1,\n output: this.output,\n invoke: this.invoke,\n description: this.description,\n tags: this.tags\n };\n }\n\n /** @internal */\n toJSON() {\n return this.definition;\n }\n\n /** The logic invoked as actors by this state node. */\n get invoke() {\n return memo(this, 'invoke', () => toArray(this.config.invoke).map((invokeConfig, i) => {\n const {\n src,\n systemId\n } = invokeConfig;\n const resolvedId = invokeConfig.id ?? createInvokeId(this.id, i);\n const resolvedSrc = typeof src === 'string' ? src : `xstate.invoke.${createInvokeId(this.id, i)}`;\n return {\n ...invokeConfig,\n src: resolvedSrc,\n id: resolvedId,\n systemId: systemId,\n toJSON() {\n const {\n onDone,\n onError,\n ...invokeDefValues\n } = invokeConfig;\n return {\n ...invokeDefValues,\n type: 'xstate.invoke',\n src: resolvedSrc,\n id: resolvedId\n };\n }\n };\n }));\n }\n\n /** The mapping of events to transitions. */\n get on() {\n return memo(this, 'on', () => {\n const transitions = this.transitions;\n return [...transitions].flatMap(([descriptor, t]) => t.map(t => [descriptor, t])).reduce((map, [descriptor, transition]) => {\n map[descriptor] = map[descriptor] || [];\n map[descriptor].push(transition);\n return map;\n }, {});\n });\n }\n get after() {\n return memo(this, 'delayedTransitions', () => getDelayedTransitions(this));\n }\n get initial() {\n return memo(this, 'initial', () => formatInitialTransition(this, this.config.initial));\n }\n\n /** @internal */\n next(snapshot, event) {\n const eventType = event.type;\n const actions = [];\n let selectedTransition;\n const candidates = memo(this, `candidates-${eventType}`, () => getCandidates(this, eventType));\n for (const candidate of candidates) {\n const {\n guard\n } = candidate;\n const resolvedContext = snapshot.context;\n let guardPassed = false;\n try {\n guardPassed = !guard || evaluateGuard(guard, resolvedContext, event, snapshot);\n } catch (err) {\n const guardType = typeof guard === 'string' ? guard : typeof guard === 'object' ? guard.type : undefined;\n throw new Error(`Unable to evaluate guard ${guardType ? `'${guardType}' ` : ''}in transition for event '${eventType}' in state node '${this.id}':\\n${err.message}`);\n }\n if (guardPassed) {\n actions.push(...candidate.actions);\n selectedTransition = candidate;\n break;\n }\n }\n return selectedTransition ? [selectedTransition] : undefined;\n }\n\n /** All the event types accepted by this state node and its descendants. */\n get events() {\n return memo(this, 'events', () => {\n const {\n states\n } = this;\n const events = new Set(this.ownEvents);\n if (states) {\n for (const stateId of Object.keys(states)) {\n const state = states[stateId];\n if (state.states) {\n for (const event of state.events) {\n events.add(`${event}`);\n }\n }\n }\n }\n return Array.from(events);\n });\n }\n\n /**\n * All the events that have transitions directly from this state node.\n *\n * Excludes any inert events.\n */\n get ownEvents() {\n const events = new Set([...this.transitions.keys()].filter(descriptor => {\n return this.transitions.get(descriptor).some(transition => !(!transition.target && !transition.actions.length && !transition.reenter));\n }));\n return Array.from(events);\n }\n}\n\nconst STATE_IDENTIFIER = '#';\nclass StateMachine {\n constructor( /** The raw config used to create the machine. */\n config, implementations) {\n this.config = config;\n /** The machine's own version. */\n this.version = void 0;\n this.schemas = void 0;\n this.implementations = void 0;\n /** @internal */\n this.__xstatenode = true;\n /** @internal */\n this.idMap = new Map();\n this.root = void 0;\n this.id = void 0;\n this.states = void 0;\n this.events = void 0;\n this.id = config.id || '(machine)';\n this.implementations = {\n actors: implementations?.actors ?? {},\n actions: implementations?.actions ?? {},\n delays: implementations?.delays ?? {},\n guards: implementations?.guards ?? {}\n };\n this.version = this.config.version;\n this.schemas = this.config.schemas;\n this.transition = this.transition.bind(this);\n this.getInitialSnapshot = this.getInitialSnapshot.bind(this);\n this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);\n this.restoreSnapshot = this.restoreSnapshot.bind(this);\n this.start = this.start.bind(this);\n this.root = new StateNode(config, {\n _key: this.id,\n _machine: this\n });\n this.root._initialize();\n this.states = this.root.states; // TODO: remove!\n this.events = this.root.events;\n }\n\n /**\n * Clones this state machine with the provided implementations and merges the\n * `context` (if provided).\n *\n * @param implementations Options (`actions`, `guards`, `actors`, `delays`,\n * `context`) to recursively merge with the existing options.\n * @returns A new `StateMachine` instance with the provided implementations.\n */\n provide(implementations) {\n const {\n actions,\n guards,\n actors,\n delays\n } = this.implementations;\n return new StateMachine(this.config, {\n actions: {\n ...actions,\n ...implementations.actions\n },\n guards: {\n ...guards,\n ...implementations.guards\n },\n actors: {\n ...actors,\n ...implementations.actors\n },\n delays: {\n ...delays,\n ...implementations.delays\n }\n });\n }\n resolveState(config) {\n const resolvedStateValue = resolveStateValue(this.root, config.value);\n const nodeSet = getAllStateNodes(getStateNodes(this.root, resolvedStateValue));\n return createMachineSnapshot({\n _nodes: [...nodeSet],\n context: config.context || {},\n children: {},\n status: isInFinalState(nodeSet, this.root) ? 'done' : config.status || 'active',\n output: config.output,\n error: config.error,\n historyValue: config.historyValue\n }, this);\n }\n\n /**\n * Determines the next snapshot given the current `snapshot` and received\n * `event`. Calculates a full macrostep from all microsteps.\n *\n * @param snapshot The current snapshot\n * @param event The received event\n */\n transition(snapshot, event, actorScope) {\n return macrostep(snapshot, event, actorScope).snapshot;\n }\n\n /**\n * Determines the next state given the current `state` and `event`. Calculates\n * a microstep.\n *\n * @param state The current state\n * @param event The received event\n */\n microstep(snapshot, event, actorScope) {\n return macrostep(snapshot, event, actorScope).microstates;\n }\n getTransitionData(snapshot, event) {\n return transitionNode(this.root, snapshot.value, snapshot, event) || [];\n }\n\n /**\n * The initial state _before_ evaluating any microsteps. This \"pre-initial\"\n * state is provided to initial actions executed in the initial state.\n */\n getPreInitialState(actorScope, initEvent, internalQueue) {\n const {\n context\n } = this.config;\n const preInitial = createMachineSnapshot({\n context: typeof context !== 'function' && context ? context : {},\n _nodes: [this.root],\n children: {},\n status: 'active'\n }, this);\n if (typeof context === 'function') {\n const assignment = ({\n spawn,\n event,\n self\n }) => context({\n spawn,\n input: event.input,\n self\n });\n return resolveActionsAndContext(preInitial, initEvent, actorScope, [assign(assignment)], internalQueue);\n }\n return preInitial;\n }\n\n /**\n * Returns the initial `State` instance, with reference to `self` as an\n * `ActorRef`.\n */\n getInitialSnapshot(actorScope, input) {\n const initEvent = createInitEvent(input); // TODO: fix;\n const internalQueue = [];\n const preInitialState = this.getPreInitialState(actorScope, initEvent, internalQueue);\n const nextState = microstep([{\n target: [...getInitialStateNodes(this.root)],\n source: this.root,\n reenter: true,\n actions: [],\n eventType: null,\n toJSON: null // TODO: fix\n }], preInitialState, actorScope, initEvent, true, internalQueue);\n const {\n snapshot: macroState\n } = macrostep(nextState, initEvent, actorScope, internalQueue);\n return macroState;\n }\n start(snapshot) {\n Object.values(snapshot.children).forEach(child => {\n if (child.getSnapshot().status === 'active') {\n child.start();\n }\n });\n }\n getStateNodeById(stateId) {\n const fullPath = toStatePath(stateId);\n const relativePath = fullPath.slice(1);\n const resolvedStateId = isStateId(fullPath[0]) ? fullPath[0].slice(STATE_IDENTIFIER.length) : fullPath[0];\n const stateNode = this.idMap.get(resolvedStateId);\n if (!stateNode) {\n throw new Error(`Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`);\n }\n return getStateNodeByPath(stateNode, relativePath);\n }\n get definition() {\n return this.root.definition;\n }\n toJSON() {\n return this.definition;\n }\n getPersistedSnapshot(snapshot, options) {\n return getPersistedSnapshot(snapshot, options);\n }\n restoreSnapshot(snapshot, _actorScope) {\n const children = {};\n const snapshotChildren = snapshot.children;\n Object.keys(snapshotChildren).forEach(actorId => {\n const actorData = snapshotChildren[actorId];\n const childState = actorData.snapshot;\n const src = actorData.src;\n const logic = typeof src === 'string' ? resolveReferencedActor(this, src) : src;\n if (!logic) {\n return;\n }\n const actorRef = createActor(logic, {\n id: actorId,\n parent: _actorScope.self,\n syncSnapshot: actorData.syncSnapshot,\n snapshot: childState,\n src,\n systemId: actorData.systemId\n });\n children[actorId] = actorRef;\n });\n const restoredSnapshot = createMachineSnapshot({\n ...snapshot,\n children,\n _nodes: Array.from(getAllStateNodes(getStateNodes(this.root, snapshot.value)))\n }, this);\n let seen = new Set();\n function reviveContext(contextPart, children) {\n if (seen.has(contextPart)) {\n return;\n }\n seen.add(contextPart);\n for (let key in contextPart) {\n const value = contextPart[key];\n if (value && typeof value === 'object') {\n if ('xstate$$type' in value && value.xstate$$type === $$ACTOR_TYPE) {\n contextPart[key] = children[value.id];\n continue;\n }\n reviveContext(value, children);\n }\n }\n }\n reviveContext(restoredSnapshot.context, children);\n return restoredSnapshot;\n }\n}\n\n/**\n * Asserts that the given event object is of the specified type or types. Throws\n * an error if the event object is not of the specified types.\n *\n * @example\n *\n * ```ts\n * // ...\n * entry: ({ event }) => {\n * assertEvent(event, 'doNothing');\n * // event is { type: 'doNothing' }\n * },\n * // ...\n * exit: ({ event }) => {\n * assertEvent(event, 'greet');\n * // event is { type: 'greet'; message: string }\n *\n * assertEvent(event, ['greet', 'notify']);\n * // event is { type: 'greet'; message: string }\n * // or { type: 'notify'; message: string; level: 'info' | 'error' }\n * },\n * ```\n */\nfunction assertEvent(event, type) {\n const types = toArray(type);\n if (!types.includes(event.type)) {\n const typesText = types.length === 1 ? `type \"${types[0]}\"` : `one of types \"${types.join('\", \"')}\"`;\n throw new Error(`Expected event ${JSON.stringify(event)} to have ${typesText}`);\n }\n}\n\n// this is not 100% accurate since we can't make parallel regions required in the result\n// `TTestValue` doesn't encode this information anyhow for us to be able to do that\n// this is fine for most practical use cases anyway though\n/**\n * Creates a state machine (statechart) with the given configuration.\n *\n * The state machine represents the pure logic of a state machine actor.\n *\n * @example\n *\n * ```ts\n * import { createMachine } from 'xstate';\n *\n * const lightMachine = createMachine({\n * id: 'light',\n * initial: 'green',\n * states: {\n * green: {\n * on: {\n * TIMER: { target: 'yellow' }\n * }\n * },\n * yellow: {\n * on: {\n * TIMER: { target: 'red' }\n * }\n * },\n * red: {\n * on: {\n * TIMER: { target: 'green' }\n * }\n * }\n * }\n * });\n *\n * const lightActor = createActor(lightMachine);\n * lightActor.start();\n *\n * lightActor.send({ type: 'TIMER' });\n * ```\n *\n * @param config The state machine configuration.\n * @param options DEPRECATED: use `setup({ ... })` or `machine.provide({ ... })`\n * to provide machine implementations instead.\n */\nfunction createMachine(config, implementations) {\n return new StateMachine(config, implementations);\n}\n\n/** @internal */\nfunction createInertActorScope(actorLogic) {\n const self = createActor(actorLogic);\n const inertActorScope = {\n self,\n defer: () => {},\n id: '',\n logger: () => {},\n sessionId: '',\n stopChild: () => {},\n system: self.system,\n emit: () => {}\n };\n return inertActorScope;\n}\nfunction getInitialSnapshot(actorLogic, ...[input]) {\n const actorScope = createInertActorScope(actorLogic);\n return actorLogic.getInitialSnapshot(actorScope, input);\n}\n\n/**\n * Determines the next snapshot for the given `actorLogic` based on the given\n * `snapshot` and `event`.\n *\n * If the `snapshot` is `undefined`, the initial snapshot of the `actorLogic` is\n * used.\n *\n * @example\n *\n * ```ts\n * import { getNextSnapshot } from 'xstate';\n * import { trafficLightMachine } from './trafficLightMachine.ts';\n *\n * const nextSnapshot = getNextSnapshot(\n * trafficLightMachine, // actor logic\n * undefined, // snapshot (or initial state if undefined)\n * { type: 'TIMER' }\n * ); // event object\n *\n * console.log(nextSnapshot.value);\n * // => 'yellow'\n *\n * const nextSnapshot2 = getNextSnapshot(\n * trafficLightMachine, // actor logic\n * nextSnapshot, // snapshot\n * { type: 'TIMER' }\n * ); // event object\n *\n * console.log(nextSnapshot2.value);\n * // =>'red'\n * ```\n */\nfunction getNextSnapshot(actorLogic, snapshot, event) {\n const inertActorScope = createInertActorScope(actorLogic);\n inertActorScope.self._snapshot = snapshot;\n return actorLogic.transition(snapshot, event, inertActorScope);\n}\n\n// at the moment we allow extra actors - ones that are not specified by `children`\n// this could be reconsidered in the future\nfunction setup({\n schemas,\n actors,\n actions,\n guards,\n delays\n}) {\n return {\n createMachine: config => createMachine({\n ...config,\n schemas\n }, {\n actors,\n actions,\n guards,\n delays\n })\n };\n}\n\n/**\n * Returns a promise that resolves to the `output` of the actor when it is done.\n *\n * @example\n *\n * ```ts\n * const machine = createMachine({\n * // ...\n * output: {\n * count: 42\n * }\n * });\n *\n * const actor = createActor(machine);\n *\n * actor.start();\n *\n * const output = await toPromise(actor);\n *\n * console.log(output);\n * // logs { count: 42 }\n * ```\n */\nfunction toPromise(actor) {\n return new Promise((resolve, reject) => {\n actor.subscribe({\n complete: () => {\n resolve(actor.getSnapshot().output);\n },\n error: reject\n });\n });\n}\n\nconst defaultWaitForOptions = {\n timeout: Infinity // much more than 10 seconds\n};\n\n/**\n * Subscribes to an actor ref and waits for its emitted value to satisfy a\n * predicate, and then resolves with that value. Will throw if the desired state\n * is not reached after an optional timeout. (defaults to Infinity).\n *\n * @example\n *\n * ```js\n * const state = await waitFor(someService, (state) => {\n * return state.hasTag('loaded');\n * });\n *\n * state.hasTag('loaded'); // true\n * ```\n *\n * @param actorRef The actor ref to subscribe to\n * @param predicate Determines if a value matches the condition to wait for\n * @param options\n * @returns A promise that eventually resolves to the emitted value that matches\n * the condition\n */\nfunction waitFor(actorRef, predicate, options) {\n const resolvedOptions = {\n ...defaultWaitForOptions,\n ...options\n };\n return new Promise((res, rej) => {\n let done = false;\n const handle = resolvedOptions.timeout === Infinity ? undefined : setTimeout(() => {\n sub.unsubscribe();\n rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`));\n }, resolvedOptions.timeout);\n const dispose = () => {\n clearTimeout(handle);\n done = true;\n sub?.unsubscribe();\n };\n function checkEmitted(emitted) {\n if (predicate(emitted)) {\n dispose();\n res(emitted);\n }\n }\n let sub; // avoid TDZ when disposing synchronously\n\n // See if the current snapshot already matches the predicate\n checkEmitted(actorRef.getSnapshot());\n if (done) {\n return;\n }\n sub = actorRef.subscribe({\n next: checkEmitted,\n error: err => {\n dispose();\n rej(err);\n },\n complete: () => {\n dispose();\n rej(new Error(`Actor terminated without satisfying predicate`));\n }\n });\n if (done) {\n sub.unsubscribe();\n }\n });\n}\n\nexport { SimulatedClock, StateMachine, StateNode, assertEvent, createMachine, getInitialSnapshot, getNextSnapshot, setup, toPromise, waitFor };\n","import { fromStream } from \"mobx-utils\";\nimport { assign, createActor, enqueueActions, fromPromise, setup } from \"xstate\";\nimport { Section } from \"./types\";\nimport { Step } from \"../steps/v2/step\";\nimport { debugLog } from \"@/lib/log\";\n\nexport type AvatarMediaEvent =\n | { type: \"mediaCanPlay\" }\n | { type: \"mediaPlaying\" }\n | { type: \"mediaPaused\" }\n | { type: \"mediaFinished\" };\n\nexport type AvatarEvent =\n | { type: \"timeUpdate\"; currentTime: number }\n | { type: \"mediaElementInitialized\" }\n | { type: \"stepTransition\"; step: Step }\n | { type: \"sectionTransition\"; section: Section; step: Step; playSettings: PlaySettings }\n | { type: \"playClicked\" }\n | { type: \"systemPlay\" }\n | { type: \"pauseClicked\" }\n | { type: \"systemPause\" }\n | { type: \"skipClicked\" }\n | { type: \"replayClicked\" }\n | { type: \"dismissClicked\" }\n | { type: \"minimize\" }\n | { type: \"expand\" }\n | { type: \"terminate\" }\n | AvatarMediaEvent;\n\nexport type PlaySettings = {\n autoPlay: boolean;\n};\n\nexport interface AvatarContext {\n currentTime: number;\n\n isMediaElementAlreadyInitialized: boolean;\n playSettings?: PlaySettings;\n section?: Section;\n step?: Step;\n}\n\nexport interface AvatarHooks {\n onAutoPlayMedia?: () => Promise;\n onPlayMedia?: () => void;\n onPauseMedia?: () => void;\n onSkipStep?: (step: Step) => void;\n onReplayStep?: (step: Step) => void;\n onSyncMediaElementCurrentTime?: (time: number) => void;\n onFinishMedia?: () => void;\n}\n\nexport interface CreateAvatarMachineParams {\n hooks?: AvatarHooks;\n}\n\nexport const createAvatarActor = ({ hooks }: CreateAvatarMachineParams) => {\n const machine = setup({\n types: {\n events: {} as AvatarEvent,\n context: {} as AvatarContext,\n },\n guards: {\n isNotBlockingStep: ({ context }) => {\n const { step } = context;\n return !!step && !step.isBlockingStepType;\n },\n canReplay: ({ context }) => {\n const { step, currentTime } = context;\n if (!step) return false;\n const isEndOfStep = currentTime >= step.end;\n const isAtomStep = step.start == step.end;\n return step.isBlocking && isEndOfStep && !isAtomStep;\n },\n canPlay: ({ context }) => {\n const { currentTime, section, step } = context;\n if (!step || !section) return false;\n const isEndOfMedia = currentTime >= section.mediaDuration;\n const isEndOfStep = currentTime >= step.end;\n return !isEndOfMedia && (!step.isBlocking || !isEndOfStep);\n },\n shouldAutoPlay: ({ context }) => {\n const { playSettings } = context;\n return playSettings?.autoPlay ?? false;\n },\n isMediaElementAlreadyInitialized: ({ context }) => {\n return context.isMediaElementAlreadyInitialized;\n },\n isMediaFinished: ({ context }) => {\n const { currentTime, section } = context;\n if (!section) return false;\n return currentTime >= section.mediaDuration;\n },\n },\n actions: {\n setCurrentTime: assign(({ context, event }) => {\n if (event.type === \"timeUpdate\") {\n return { ...context, currentTime: event.currentTime };\n }\n return context;\n }),\n setCurrentSection: assign(({ context, event }) => {\n if (event.type === \"sectionTransition\") {\n return {\n ...context,\n section: event.section,\n step: event.step,\n playSettings: event.playSettings,\n isMediaElementAlreadyInitialized: event.section.id === context.section?.id,\n };\n }\n return context;\n }),\n setCurrentStep: assign(({ context, event }) => {\n if (event.type === \"stepTransition\") {\n return { ...context, step: event.step };\n }\n return context;\n }),\n skipStep: ({ context }) => {\n const { step } = context;\n hooks?.onSkipStep?.(step!);\n },\n playMedia: () => {\n debugLog(\"playing media\");\n hooks?.onPlayMedia?.();\n },\n pauseMedia: () => {\n debugLog(\"pausing media\");\n hooks?.onPauseMedia?.();\n },\n finishMedia: () => {\n hooks?.onFinishMedia?.();\n },\n replayStep: ({ context }) => {\n const { step } = context;\n debugLog(\"replaying step\");\n hooks?.onReplayStep?.(step!);\n },\n syncMediaElementCurrentTime: ({ context }) => {\n hooks?.onSyncMediaElementCurrentTime?.(context.currentTime);\n },\n },\n actors: {\n tryAutoPlay: fromPromise(async () => {\n if (hooks?.onAutoPlayMedia) {\n return await hooks.onAutoPlayMedia();\n }\n return Promise.resolve();\n }),\n },\n }).createMachine({\n /** @xstate-layout N4IgpgJg5mDOIC5QEMBuyAuyBOBiDAlgLZgCqADhJmANoAMAuoqOQPawGGsB2zIAHogCMQgBwA2AHQBmAJwAWIbPHiATPPUBWADQgAnogC0qudMmrZ0upoDsN6Zs1qAvs91pMOXLDABjLtwAKtjI3BwB9ExIIGzhBDx8ggjSorLmViZWmlY2mqq6BgiGQuJ0NpLKoo4mskqqQtKu7uhYeLAYYOTBoXE8kXyxnPG80UlC8pqiknQmNrWqqhILOvpG6nRpslqidGJyotLyTSAerfhg2EQE3NT90YMBiWvi5UIbGrK5NmWLBYiKUjouyE32sjicNmOpy8V24xAIAC9aIwBuwhglRohFnJJCJRPIXjYJJotn8EHZVBUZnUUvJrPJGm4Ti0cJJrkNkAAbRHXKCSCB+AgCgDqyCG3CgADFWNgALKQAjIACinLAJG4GAAknDCFzEZhhrg7iw0Y9MQgDppJPIqjbdjZFiT8qsiuNNPJzLUshZxPIbEIoSzsGydYruQjefzBSKxYQJdK5Qrlar1VrQ3qEQaeEahFETb0RqAxqpJpJHBNNHtspYycUJh6LEJFqp-Q7UpCmdDg+zdeHIwB3WMJgDKfgC3TC6O43jHwwnBeNMVNwyeFtS1rU1hLdAc4lEQlrYhmkj3eX9eUOckDnm76b7Eskg84CflEEVKrVYA12o54az05IN9k0-b870RSBFweFdzSbepJCJDZxFkCRrGkBpDwWIRpgmKxRBbF4r07IMQ1-HkH1gPRuF8V93xTL8MAAYQAV2wbB6MCYgwCNFF7mXDEi0QSwpHqWRZB3ISlHkeRDzoP1rRbMSgWkOZSlUa9WkkbAmO4OEJW8ABrAhyAY7lfH0iCePzKdVzwk80I2aRMIWeoZOQ+CJD9Jt5C2FQO2aG9NO03SoFwQDFUldlYAACwsvMlwLVd6nELDbEsUTpCsWCyTeNI6CqFJviQ1Q93GdTWS0nTIwFXwhTAABBJiMFYAAFTlkD0bi4qg-iBEQUQJBkUobSk5C7BeWsHToE9ljsXYCTwo4iICirgqjGqBQaprWvanMur4wteoQYqPRJeZ7CbJwDxdQxJumktZvGPd1DK4MVsjZBGpatqOogHgwBDVBWHMyQPq277IP21cFCmfFHDQmwATEWs6Smor9xKBGZjmF7Asqh9Qa+naLmwGVJHINqMAAMxlIgQc+7a9AhhLzXEDLPT9FRmw0Jta2yMwDjKfcJhKBw1KWjS3ofcn2po5BOtRZmBIQN1KSqZK7FsCwqmdQpihSeClFyfEkIkOZFv8iWgsjNjpb0YcOnIbw9HaNUGaZ6yYOWeCbXhuxlKJaSXUcipDlmjK9wc0QcclvknwwF8kwZ3lQsT77eXds0lbxV5UiBEbZNsQPdcw6Y6CKl4kImA5o6tqW0708gPp8EyCDM2KFY9rOsYqcYtgBEs0KLoxximkSbCQ31ubUWQa7xvlbeTiiXaIZqm+RPbFcOjyT281ISwaJRWcPOlzENrZx5Kako-F8ra-ntfZfl3jN6SZC0jVulJkmLJxGynEL-6lseoeUGSz1WtVWqDMADy2AIpwmio-DO0Es5zFyjsHY48dxSRKGSX0MgCRzAQm8MQeEwFVWjGAaBsDIpRUQbmDumdDpiBKCeJsZcVAV1sDYY+J5SgbBBCSRQJQthkKlmvCAuBbYtzbhAJBPUxiOCwhMIkYkST8KRi6YqqsTALFkE4Q4IDxCiPvkxHwEibbfWkeZWRll4qdyYSCKa+48rJWsAcbyOssRqEkHhNC2QCRHhETfV6d8ybiKdsvN2tjuoHTGAteCFgB7eTmIcFYhQtE+JMEIfxyUdhBItrfOeYTTGQEfEOGUstV4lJTkBKpZi5GxMEk4HxIJHLJSQtYHcZInBTEQiWP0slvgpGMcUsxkhYTwiRBIsA-BG7cBsRvexSRip4LyOwokrMGSyFwQcA23lKyszQhYPyzJlqhMbiUiA4z2RXCmbgN8sAriwFgFY9uz8lnCAMbibIsxxKqTJBSKkCwDi5BcRoEZFyxlxwTIEC4sJ-znEuNcW40TIbmlmPBISvpz7czygCh0QKGgHHGCkaQRjgm41WpC0pYVkBwIINFSAM5-BzhCJOCIqKX5Ykch6OYeUZjiE0GXP0aS+pSAcP1TcCENYz2ONwVgAp4DRC7Aw5Bh1DAZStJaUSCgiRC2yLWeo9hpi1ErgyKSjICm3lIhGCUqr5GIARlIT4dg3gWCsGoaQhq8pWhJK0xwokRU4x7GGMifIIExnFFKCpSYPyph-L2fUjCYmrjNhUOw-oZiWDLiYQ8X9zCKGzbYDKuFg1gVtbHcp2BRwsp4POexKbzQSDMKpUETZBVKFFa6USvTahjXHhMVQO4y02oHFW2Wcb6IJtDZmZNaKs5iHKIoOQ4wpLNj0YeUW5hgTnVsMlBoI7E0VskBRKiE66IamYqxdinF7WNItHBOYOx+WWHqKIDCUkyw4QcHkdQJRNDGLvauEl0wVAZQmIK-0GRayiUpD+ko+rdipBGRG+q9NvpAabZ8UuqQhWbN9IKmDskfHVAcm8YVlrTmWyKQTBmmGlb4leMW7+6hWb+l5qWAW3x9yCtKJ8CF31Zb0aYXSMwl9x6swUB49910JhUiUGJf0Yg10OBGRY9q9tOjCeLA0aYerxhKAaESbK4x4LJVUahPCxVKNdkpWO58Mban1ygNpz5ei9N2lyazMoXrrolyBJXWwDRHAbAE+1XkrmECfAbGJFCeRhozENbprRKz3QOEOAGClMdRlgCE+8xhr9ioVDUOPQqvpchXV1nJsSCmyh4hUwBrLoTUNUPpQgpMkWQTj2mBlVINoUmfBk4UMQVoCQXg8kSJs18rV2bEZczrtRQOHIg0F6DQd8Q728o5PKDRZLkpm9l6lVyhSqki8hK0+GyVWAKpWXBcwyy+jJVofd5sqOFKpeInLEAEwABEGXIAAEaqggJtQmhQrIFe5blMDqTIO7c8QgP0lJV2BoJIcHVELPvQsc4qOpYAztkpkJNDYHkOZD0RwSlHUnNkY6a0Uo7dMwbtUlGKYHkXWZYWyYoBGQqfnITJEj3EI1qeqbpx9y51y4S3MgJFkwpYMtekmA6YzLoEZpDpAsfhjh+r1ExxL7H2BYVIpuHOrlCAXhWhBGIAeGbx7bNVwSsSCxQX8McmLA75zPu0razFCAsumzlGQrMMaLYAQC8pxMMog6HSwRxh0Y31A-f5bVUkYwohyjasDfpnC+KsKCvqMpHbaPFquCAA */\n id: \"avatar\",\n initial: \"initializing\",\n context: () => ({\n currentTime: 0,\n isMediaElementAlreadyInitialized: false,\n }),\n on: {\n timeUpdate: {\n actions: \"setCurrentTime\",\n },\n sectionTransition: {\n actions: \"setCurrentSection\",\n target: \".initializing.decideWaitingForMediaElementInitialization\",\n },\n stepTransition: {\n actions: \"setCurrentStep\",\n },\n terminate: {\n target: \".terminated\",\n },\n minimize: {\n target: \".running.paused.minimized\",\n },\n },\n states: {\n initializing: {\n initial: \"waitForSectionTransition\",\n states: {\n decideWaitingForMediaElementInitialization: {\n always: [\n {\n guard: \"isMediaElementAlreadyInitialized\",\n target: \"syncMediaElementCurrentTime\",\n },\n {\n target: \"waitForMediaElementInitialization\",\n },\n ],\n },\n waitForSectionTransition: {\n on: {\n sectionTransition: {\n actions: \"setCurrentSection\",\n target: \"decideWaitingForMediaElementInitialization\",\n },\n },\n },\n waitForMediaElementInitialization: {\n on: {\n mediaElementInitialized: {\n target: \"syncMediaElementCurrentTime\",\n },\n },\n },\n syncMediaElementCurrentTime: {\n entry: \"syncMediaElementCurrentTime\",\n always: \"#avatar.running.decideAutoPlay\",\n description: \"Seeks media element to current time\",\n },\n },\n },\n running: {\n initial: \"decideAutoPlay\",\n on: {\n skipClicked: {\n guard: \"isNotBlockingStep\",\n actions: \"skipStep\",\n },\n mediaFinished: {\n target: \".paused.mediaFinished\",\n },\n },\n states: {\n decideAutoPlay: {\n always: [\n {\n guard: \"shouldAutoPlay\",\n target: \"autoPlay\",\n },\n {\n target: \"paused.pausedForDisabledAutoPlay\",\n },\n ],\n },\n autoPlay: {\n invoke: {\n id: \"autoPlay\",\n src: \"tryAutoPlay\",\n onDone: {\n target: \"playing\",\n },\n onError: {\n target: \"paused.autoPlayFailed\",\n },\n },\n },\n playMedia: {\n entry: \"playMedia\",\n\n always: {\n target: \"waitForMediaPlaying\",\n },\n },\n replayStep: {\n entry: \"replayStep\",\n on: {\n systemPlay: {\n target: \"playMedia\",\n },\n },\n },\n waitForMediaPlaying: {\n on: {\n mediaPlaying: {\n target: \"playing\",\n },\n },\n },\n playing: {\n on: {\n pauseClicked: {\n target: \"pauseMedia\",\n },\n systemPause: {\n target: \"pauseMedia\",\n },\n },\n },\n pauseMedia: {\n entry: \"pauseMedia\",\n always: {\n target: \"paused.waitForMediaPause\",\n },\n },\n\n decidePlayOrFinishMedia: {\n always: [\n {\n guard: \"isMediaFinished\",\n target: \"#avatar.running.paused.mediaFinished\",\n actions: \"finishMedia\",\n },\n {\n target: \"playMedia\",\n },\n ],\n },\n paused: {\n initial: \"idle\",\n on: {\n playClicked: {\n guard: \"canPlay\",\n target: \"playMedia\",\n },\n replayClicked: {\n target: \"replayStep\",\n guard: \"canReplay\",\n },\n systemPlay: {\n target: \"decidePlayOrFinishMedia\",\n },\n },\n states: {\n idle: {},\n pausedForDisabledAutoPlay: {\n tags: [\"pausedForDisabledAutoPlay\"],\n },\n waitForMediaPause: {\n on: {\n mediaPaused: {\n target: \"idle\",\n },\n },\n },\n autoPlayFailed: {\n tags: [\"autoPlayFailed\"],\n },\n minimized: {\n tags: [\"minimized\"],\n entry: \"pauseMedia\",\n on: {\n expand: {\n target: \"#avatar.initializing.waitForSectionTransition\",\n },\n dismissClicked: {\n target: \"waitForTermination\",\n },\n },\n },\n waitForTermination: {\n on: {\n terminate: {\n target: \"#avatar.terminated\",\n },\n },\n },\n mediaFinished: {\n on: {\n sectionTransition: {\n actions: \"setCurrentSection\",\n target: \"#avatar.initializing.decideWaitingForMediaElementInitialization\",\n },\n },\n },\n },\n },\n },\n },\n terminated: {\n type: \"final\",\n },\n },\n });\n\n return createActor(machine, {\n inspect: (e) => {\n if (e.type === \"@xstate.snapshot\" && e.event.type !== \"timeUpdate\") {\n debugLog({ event: e.event, result: e.snapshot });\n }\n },\n });\n};\n\nexport const createAvatarStream = (machine: ReturnType) => fromStream(machine);\n","// NOTE: this list must be up-to-date with browsers listed in\n// test/acceptance/useragentstrings.yml\nexport const BROWSER_ALIASES_MAP = {\n 'Amazon Silk': 'amazon_silk',\n 'Android Browser': 'android',\n Bada: 'bada',\n BlackBerry: 'blackberry',\n Chrome: 'chrome',\n Chromium: 'chromium',\n Electron: 'electron',\n Epiphany: 'epiphany',\n Firefox: 'firefox',\n Focus: 'focus',\n Generic: 'generic',\n 'Google Search': 'google_search',\n Googlebot: 'googlebot',\n 'Internet Explorer': 'ie',\n 'K-Meleon': 'k_meleon',\n Maxthon: 'maxthon',\n 'Microsoft Edge': 'edge',\n 'MZ Browser': 'mz',\n 'NAVER Whale Browser': 'naver',\n Opera: 'opera',\n 'Opera Coast': 'opera_coast',\n PhantomJS: 'phantomjs',\n Puffin: 'puffin',\n QupZilla: 'qupzilla',\n QQ: 'qq',\n QQLite: 'qqlite',\n Safari: 'safari',\n Sailfish: 'sailfish',\n 'Samsung Internet for Android': 'samsung_internet',\n SeaMonkey: 'seamonkey',\n Sleipnir: 'sleipnir',\n Swing: 'swing',\n Tizen: 'tizen',\n 'UC Browser': 'uc',\n Vivaldi: 'vivaldi',\n 'WebOS Browser': 'webos',\n WeChat: 'wechat',\n 'Yandex Browser': 'yandex',\n Roku: 'roku',\n};\n\nexport const BROWSER_MAP = {\n amazon_silk: 'Amazon Silk',\n android: 'Android Browser',\n bada: 'Bada',\n blackberry: 'BlackBerry',\n chrome: 'Chrome',\n chromium: 'Chromium',\n electron: 'Electron',\n epiphany: 'Epiphany',\n firefox: 'Firefox',\n focus: 'Focus',\n generic: 'Generic',\n googlebot: 'Googlebot',\n google_search: 'Google Search',\n ie: 'Internet Explorer',\n k_meleon: 'K-Meleon',\n maxthon: 'Maxthon',\n edge: 'Microsoft Edge',\n mz: 'MZ Browser',\n naver: 'NAVER Whale Browser',\n opera: 'Opera',\n opera_coast: 'Opera Coast',\n phantomjs: 'PhantomJS',\n puffin: 'Puffin',\n qupzilla: 'QupZilla',\n qq: 'QQ Browser',\n qqlite: 'QQ Browser Lite',\n safari: 'Safari',\n sailfish: 'Sailfish',\n samsung_internet: 'Samsung Internet for Android',\n seamonkey: 'SeaMonkey',\n sleipnir: 'Sleipnir',\n swing: 'Swing',\n tizen: 'Tizen',\n uc: 'UC Browser',\n vivaldi: 'Vivaldi',\n webos: 'WebOS Browser',\n wechat: 'WeChat',\n yandex: 'Yandex Browser',\n};\n\nexport const PLATFORMS_MAP = {\n tablet: 'tablet',\n mobile: 'mobile',\n desktop: 'desktop',\n tv: 'tv',\n};\n\nexport const OS_MAP = {\n WindowsPhone: 'Windows Phone',\n Windows: 'Windows',\n MacOS: 'macOS',\n iOS: 'iOS',\n Android: 'Android',\n WebOS: 'WebOS',\n BlackBerry: 'BlackBerry',\n Bada: 'Bada',\n Tizen: 'Tizen',\n Linux: 'Linux',\n ChromeOS: 'Chrome OS',\n PlayStation4: 'PlayStation 4',\n Roku: 'Roku',\n};\n\nexport const ENGINE_MAP = {\n EdgeHTML: 'EdgeHTML',\n Blink: 'Blink',\n Trident: 'Trident',\n Presto: 'Presto',\n Gecko: 'Gecko',\n WebKit: 'WebKit',\n};\n","import { BROWSER_MAP, BROWSER_ALIASES_MAP } from './constants.js';\n\nexport default class Utils {\n /**\n * Get first matched item for a string\n * @param {RegExp} regexp\n * @param {String} ua\n * @return {Array|{index: number, input: string}|*|boolean|string}\n */\n static getFirstMatch(regexp, ua) {\n const match = ua.match(regexp);\n return (match && match.length > 0 && match[1]) || '';\n }\n\n /**\n * Get second matched item for a string\n * @param regexp\n * @param {String} ua\n * @return {Array|{index: number, input: string}|*|boolean|string}\n */\n static getSecondMatch(regexp, ua) {\n const match = ua.match(regexp);\n return (match && match.length > 1 && match[2]) || '';\n }\n\n /**\n * Match a regexp and return a constant or undefined\n * @param {RegExp} regexp\n * @param {String} ua\n * @param {*} _const Any const that will be returned if regexp matches the string\n * @return {*}\n */\n static matchAndReturnConst(regexp, ua, _const) {\n if (regexp.test(ua)) {\n return _const;\n }\n return void (0);\n }\n\n static getWindowsVersionName(version) {\n switch (version) {\n case 'NT': return 'NT';\n case 'XP': return 'XP';\n case 'NT 5.0': return '2000';\n case 'NT 5.1': return 'XP';\n case 'NT 5.2': return '2003';\n case 'NT 6.0': return 'Vista';\n case 'NT 6.1': return '7';\n case 'NT 6.2': return '8';\n case 'NT 6.3': return '8.1';\n case 'NT 10.0': return '10';\n default: return undefined;\n }\n }\n\n /**\n * Get macOS version name\n * 10.5 - Leopard\n * 10.6 - Snow Leopard\n * 10.7 - Lion\n * 10.8 - Mountain Lion\n * 10.9 - Mavericks\n * 10.10 - Yosemite\n * 10.11 - El Capitan\n * 10.12 - Sierra\n * 10.13 - High Sierra\n * 10.14 - Mojave\n * 10.15 - Catalina\n *\n * @example\n * getMacOSVersionName(\"10.14\") // 'Mojave'\n *\n * @param {string} version\n * @return {string} versionName\n */\n static getMacOSVersionName(version) {\n const v = version.split('.').splice(0, 2).map(s => parseInt(s, 10) || 0);\n v.push(0);\n if (v[0] !== 10) return undefined;\n switch (v[1]) {\n case 5: return 'Leopard';\n case 6: return 'Snow Leopard';\n case 7: return 'Lion';\n case 8: return 'Mountain Lion';\n case 9: return 'Mavericks';\n case 10: return 'Yosemite';\n case 11: return 'El Capitan';\n case 12: return 'Sierra';\n case 13: return 'High Sierra';\n case 14: return 'Mojave';\n case 15: return 'Catalina';\n default: return undefined;\n }\n }\n\n /**\n * Get Android version name\n * 1.5 - Cupcake\n * 1.6 - Donut\n * 2.0 - Eclair\n * 2.1 - Eclair\n * 2.2 - Froyo\n * 2.x - Gingerbread\n * 3.x - Honeycomb\n * 4.0 - Ice Cream Sandwich\n * 4.1 - Jelly Bean\n * 4.4 - KitKat\n * 5.x - Lollipop\n * 6.x - Marshmallow\n * 7.x - Nougat\n * 8.x - Oreo\n * 9.x - Pie\n *\n * @example\n * getAndroidVersionName(\"7.0\") // 'Nougat'\n *\n * @param {string} version\n * @return {string} versionName\n */\n static getAndroidVersionName(version) {\n const v = version.split('.').splice(0, 2).map(s => parseInt(s, 10) || 0);\n v.push(0);\n if (v[0] === 1 && v[1] < 5) return undefined;\n if (v[0] === 1 && v[1] < 6) return 'Cupcake';\n if (v[0] === 1 && v[1] >= 6) return 'Donut';\n if (v[0] === 2 && v[1] < 2) return 'Eclair';\n if (v[0] === 2 && v[1] === 2) return 'Froyo';\n if (v[0] === 2 && v[1] > 2) return 'Gingerbread';\n if (v[0] === 3) return 'Honeycomb';\n if (v[0] === 4 && v[1] < 1) return 'Ice Cream Sandwich';\n if (v[0] === 4 && v[1] < 4) return 'Jelly Bean';\n if (v[0] === 4 && v[1] >= 4) return 'KitKat';\n if (v[0] === 5) return 'Lollipop';\n if (v[0] === 6) return 'Marshmallow';\n if (v[0] === 7) return 'Nougat';\n if (v[0] === 8) return 'Oreo';\n if (v[0] === 9) return 'Pie';\n return undefined;\n }\n\n /**\n * Get version precisions count\n *\n * @example\n * getVersionPrecision(\"1.10.3\") // 3\n *\n * @param {string} version\n * @return {number}\n */\n static getVersionPrecision(version) {\n return version.split('.').length;\n }\n\n /**\n * Calculate browser version weight\n *\n * @example\n * compareVersions('1.10.2.1', '1.8.2.1.90') // 1\n * compareVersions('1.010.2.1', '1.09.2.1.90'); // 1\n * compareVersions('1.10.2.1', '1.10.2.1'); // 0\n * compareVersions('1.10.2.1', '1.0800.2'); // -1\n * compareVersions('1.10.2.1', '1.10', true); // 0\n *\n * @param {String} versionA versions versions to compare\n * @param {String} versionB versions versions to compare\n * @param {boolean} [isLoose] enable loose comparison\n * @return {Number} comparison result: -1 when versionA is lower,\n * 1 when versionA is bigger, 0 when both equal\n */\n /* eslint consistent-return: 1 */\n static compareVersions(versionA, versionB, isLoose = false) {\n // 1) get common precision for both versions, for example for \"10.0\" and \"9\" it should be 2\n const versionAPrecision = Utils.getVersionPrecision(versionA);\n const versionBPrecision = Utils.getVersionPrecision(versionB);\n\n let precision = Math.max(versionAPrecision, versionBPrecision);\n let lastPrecision = 0;\n\n const chunks = Utils.map([versionA, versionB], (version) => {\n const delta = precision - Utils.getVersionPrecision(version);\n\n // 2) \"9\" -> \"9.0\" (for precision = 2)\n const _version = version + new Array(delta + 1).join('.0');\n\n // 3) \"9.0\" -> [\"000000000\"\", \"000000009\"]\n return Utils.map(_version.split('.'), chunk => new Array(20 - chunk.length).join('0') + chunk).reverse();\n });\n\n // adjust precision for loose comparison\n if (isLoose) {\n lastPrecision = precision - Math.min(versionAPrecision, versionBPrecision);\n }\n\n // iterate in reverse order by reversed chunks array\n precision -= 1;\n while (precision >= lastPrecision) {\n // 4) compare: \"000000009\" > \"000000010\" = false (but \"9\" > \"10\" = true)\n if (chunks[0][precision] > chunks[1][precision]) {\n return 1;\n }\n\n if (chunks[0][precision] === chunks[1][precision]) {\n if (precision === lastPrecision) {\n // all version chunks are same\n return 0;\n }\n\n precision -= 1;\n } else if (chunks[0][precision] < chunks[1][precision]) {\n return -1;\n }\n }\n\n return undefined;\n }\n\n /**\n * Array::map polyfill\n *\n * @param {Array} arr\n * @param {Function} iterator\n * @return {Array}\n */\n static map(arr, iterator) {\n const result = [];\n let i;\n if (Array.prototype.map) {\n return Array.prototype.map.call(arr, iterator);\n }\n for (i = 0; i < arr.length; i += 1) {\n result.push(iterator(arr[i]));\n }\n return result;\n }\n\n /**\n * Array::find polyfill\n *\n * @param {Array} arr\n * @param {Function} predicate\n * @return {Array}\n */\n static find(arr, predicate) {\n let i;\n let l;\n if (Array.prototype.find) {\n return Array.prototype.find.call(arr, predicate);\n }\n for (i = 0, l = arr.length; i < l; i += 1) {\n const value = arr[i];\n if (predicate(value, i)) {\n return value;\n }\n }\n return undefined;\n }\n\n /**\n * Object::assign polyfill\n *\n * @param {Object} obj\n * @param {Object} ...objs\n * @return {Object}\n */\n static assign(obj, ...assigners) {\n const result = obj;\n let i;\n let l;\n if (Object.assign) {\n return Object.assign(obj, ...assigners);\n }\n for (i = 0, l = assigners.length; i < l; i += 1) {\n const assigner = assigners[i];\n if (typeof assigner === 'object' && assigner !== null) {\n const keys = Object.keys(assigner);\n keys.forEach((key) => {\n result[key] = assigner[key];\n });\n }\n }\n return obj;\n }\n\n /**\n * Get short version/alias for a browser name\n *\n * @example\n * getBrowserAlias('Microsoft Edge') // edge\n *\n * @param {string} browserName\n * @return {string}\n */\n static getBrowserAlias(browserName) {\n return BROWSER_ALIASES_MAP[browserName];\n }\n\n /**\n * Get short version/alias for a browser name\n *\n * @example\n * getBrowserAlias('edge') // Microsoft Edge\n *\n * @param {string} browserAlias\n * @return {string}\n */\n static getBrowserTypeByAlias(browserAlias) {\n return BROWSER_MAP[browserAlias] || '';\n }\n}\n","/**\n * Browsers' descriptors\n *\n * The idea of descriptors is simple. You should know about them two simple things:\n * 1. Every descriptor has a method or property called `test` and a `describe` method.\n * 2. Order of descriptors is important.\n *\n * More details:\n * 1. Method or property `test` serves as a way to detect whether the UA string\n * matches some certain browser or not. The `describe` method helps to make a result\n * object with params that show some browser-specific things: name, version, etc.\n * 2. Order of descriptors is important because a Parser goes through them one by one\n * in course. For example, if you insert Chrome's descriptor as the first one,\n * more then a half of browsers will be described as Chrome, because they will pass\n * the Chrome descriptor's test.\n *\n * Descriptor's `test` could be a property with an array of RegExps, where every RegExp\n * will be applied to a UA string to test it whether it matches or not.\n * If a descriptor has two or more regexps in the `test` array it tests them one by one\n * with a logical sum operation. Parser stops if it has found any RegExp that matches the UA.\n *\n * Or `test` could be a method. In that case it gets a Parser instance and should\n * return true/false to get the Parser know if this browser descriptor matches the UA or not.\n */\n\nimport Utils from './utils.js';\n\nconst commonVersionIdentifier = /version\\/(\\d+(\\.?_?\\d+)+)/i;\n\nconst browsersList = [\n /* Googlebot */\n {\n test: [/googlebot/i],\n describe(ua) {\n const browser = {\n name: 'Googlebot',\n };\n const version = Utils.getFirstMatch(/googlebot\\/(\\d+(\\.\\d+))/i, ua) || Utils.getFirstMatch(commonVersionIdentifier, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n\n /* Opera < 13.0 */\n {\n test: [/opera/i],\n describe(ua) {\n const browser = {\n name: 'Opera',\n };\n const version = Utils.getFirstMatch(commonVersionIdentifier, ua) || Utils.getFirstMatch(/(?:opera)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n\n /* Opera > 13.0 */\n {\n test: [/opr\\/|opios/i],\n describe(ua) {\n const browser = {\n name: 'Opera',\n };\n const version = Utils.getFirstMatch(/(?:opr|opios)[\\s/](\\S+)/i, ua) || Utils.getFirstMatch(commonVersionIdentifier, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/SamsungBrowser/i],\n describe(ua) {\n const browser = {\n name: 'Samsung Internet for Android',\n };\n const version = Utils.getFirstMatch(commonVersionIdentifier, ua) || Utils.getFirstMatch(/(?:SamsungBrowser)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/Whale/i],\n describe(ua) {\n const browser = {\n name: 'NAVER Whale Browser',\n };\n const version = Utils.getFirstMatch(commonVersionIdentifier, ua) || Utils.getFirstMatch(/(?:whale)[\\s/](\\d+(?:\\.\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/MZBrowser/i],\n describe(ua) {\n const browser = {\n name: 'MZ Browser',\n };\n const version = Utils.getFirstMatch(/(?:MZBrowser)[\\s/](\\d+(?:\\.\\d+)+)/i, ua) || Utils.getFirstMatch(commonVersionIdentifier, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/focus/i],\n describe(ua) {\n const browser = {\n name: 'Focus',\n };\n const version = Utils.getFirstMatch(/(?:focus)[\\s/](\\d+(?:\\.\\d+)+)/i, ua) || Utils.getFirstMatch(commonVersionIdentifier, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/swing/i],\n describe(ua) {\n const browser = {\n name: 'Swing',\n };\n const version = Utils.getFirstMatch(/(?:swing)[\\s/](\\d+(?:\\.\\d+)+)/i, ua) || Utils.getFirstMatch(commonVersionIdentifier, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/coast/i],\n describe(ua) {\n const browser = {\n name: 'Opera Coast',\n };\n const version = Utils.getFirstMatch(commonVersionIdentifier, ua) || Utils.getFirstMatch(/(?:coast)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/opt\\/\\d+(?:.?_?\\d+)+/i],\n describe(ua) {\n const browser = {\n name: 'Opera Touch',\n };\n const version = Utils.getFirstMatch(/(?:opt)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua) || Utils.getFirstMatch(commonVersionIdentifier, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/yabrowser/i],\n describe(ua) {\n const browser = {\n name: 'Yandex Browser',\n };\n const version = Utils.getFirstMatch(/(?:yabrowser)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua) || Utils.getFirstMatch(commonVersionIdentifier, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/ucbrowser/i],\n describe(ua) {\n const browser = {\n name: 'UC Browser',\n };\n const version = Utils.getFirstMatch(commonVersionIdentifier, ua) || Utils.getFirstMatch(/(?:ucbrowser)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/Maxthon|mxios/i],\n describe(ua) {\n const browser = {\n name: 'Maxthon',\n };\n const version = Utils.getFirstMatch(commonVersionIdentifier, ua) || Utils.getFirstMatch(/(?:Maxthon|mxios)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/epiphany/i],\n describe(ua) {\n const browser = {\n name: 'Epiphany',\n };\n const version = Utils.getFirstMatch(commonVersionIdentifier, ua) || Utils.getFirstMatch(/(?:epiphany)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/puffin/i],\n describe(ua) {\n const browser = {\n name: 'Puffin',\n };\n const version = Utils.getFirstMatch(commonVersionIdentifier, ua) || Utils.getFirstMatch(/(?:puffin)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/sleipnir/i],\n describe(ua) {\n const browser = {\n name: 'Sleipnir',\n };\n const version = Utils.getFirstMatch(commonVersionIdentifier, ua) || Utils.getFirstMatch(/(?:sleipnir)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/k-meleon/i],\n describe(ua) {\n const browser = {\n name: 'K-Meleon',\n };\n const version = Utils.getFirstMatch(commonVersionIdentifier, ua) || Utils.getFirstMatch(/(?:k-meleon)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/micromessenger/i],\n describe(ua) {\n const browser = {\n name: 'WeChat',\n };\n const version = Utils.getFirstMatch(/(?:micromessenger)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua) || Utils.getFirstMatch(commonVersionIdentifier, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/qqbrowser/i],\n describe(ua) {\n const browser = {\n name: (/qqbrowserlite/i).test(ua) ? 'QQ Browser Lite' : 'QQ Browser',\n };\n const version = Utils.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\\d+(\\.?_?\\d+)+)/i, ua) || Utils.getFirstMatch(commonVersionIdentifier, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/msie|trident/i],\n describe(ua) {\n const browser = {\n name: 'Internet Explorer',\n };\n const version = Utils.getFirstMatch(/(?:msie |rv:)(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/\\sedg\\//i],\n describe(ua) {\n const browser = {\n name: 'Microsoft Edge',\n };\n\n const version = Utils.getFirstMatch(/\\sedg\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/edg([ea]|ios)/i],\n describe(ua) {\n const browser = {\n name: 'Microsoft Edge',\n };\n\n const version = Utils.getSecondMatch(/edg([ea]|ios)\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/vivaldi/i],\n describe(ua) {\n const browser = {\n name: 'Vivaldi',\n };\n const version = Utils.getFirstMatch(/vivaldi\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/seamonkey/i],\n describe(ua) {\n const browser = {\n name: 'SeaMonkey',\n };\n const version = Utils.getFirstMatch(/seamonkey\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/sailfish/i],\n describe(ua) {\n const browser = {\n name: 'Sailfish',\n };\n\n const version = Utils.getFirstMatch(/sailfish\\s?browser\\/(\\d+(\\.\\d+)?)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/silk/i],\n describe(ua) {\n const browser = {\n name: 'Amazon Silk',\n };\n const version = Utils.getFirstMatch(/silk\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/phantom/i],\n describe(ua) {\n const browser = {\n name: 'PhantomJS',\n };\n const version = Utils.getFirstMatch(/phantomjs\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/slimerjs/i],\n describe(ua) {\n const browser = {\n name: 'SlimerJS',\n };\n const version = Utils.getFirstMatch(/slimerjs\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/blackberry|\\bbb\\d+/i, /rim\\stablet/i],\n describe(ua) {\n const browser = {\n name: 'BlackBerry',\n };\n const version = Utils.getFirstMatch(commonVersionIdentifier, ua) || Utils.getFirstMatch(/blackberry[\\d]+\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/(web|hpw)[o0]s/i],\n describe(ua) {\n const browser = {\n name: 'WebOS Browser',\n };\n const version = Utils.getFirstMatch(commonVersionIdentifier, ua) || Utils.getFirstMatch(/w(?:eb)?[o0]sbrowser\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/bada/i],\n describe(ua) {\n const browser = {\n name: 'Bada',\n };\n const version = Utils.getFirstMatch(/dolfin\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/tizen/i],\n describe(ua) {\n const browser = {\n name: 'Tizen',\n };\n const version = Utils.getFirstMatch(/(?:tizen\\s?)?browser\\/(\\d+(\\.?_?\\d+)+)/i, ua) || Utils.getFirstMatch(commonVersionIdentifier, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/qupzilla/i],\n describe(ua) {\n const browser = {\n name: 'QupZilla',\n };\n const version = Utils.getFirstMatch(/(?:qupzilla)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua) || Utils.getFirstMatch(commonVersionIdentifier, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/firefox|iceweasel|fxios/i],\n describe(ua) {\n const browser = {\n name: 'Firefox',\n };\n const version = Utils.getFirstMatch(/(?:firefox|iceweasel|fxios)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/electron/i],\n describe(ua) {\n const browser = {\n name: 'Electron',\n };\n const version = Utils.getFirstMatch(/(?:electron)\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/MiuiBrowser/i],\n describe(ua) {\n const browser = {\n name: 'Miui',\n };\n const version = Utils.getFirstMatch(/(?:MiuiBrowser)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/chromium/i],\n describe(ua) {\n const browser = {\n name: 'Chromium',\n };\n const version = Utils.getFirstMatch(/(?:chromium)[\\s/](\\d+(\\.?_?\\d+)+)/i, ua) || Utils.getFirstMatch(commonVersionIdentifier, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/chrome|crios|crmo/i],\n describe(ua) {\n const browser = {\n name: 'Chrome',\n };\n const version = Utils.getFirstMatch(/(?:chrome|crios|crmo)\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n {\n test: [/GSA/i],\n describe(ua) {\n const browser = {\n name: 'Google Search',\n };\n const version = Utils.getFirstMatch(/(?:GSA)\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n\n /* Android Browser */\n {\n test(parser) {\n const notLikeAndroid = !parser.test(/like android/i);\n const butAndroid = parser.test(/android/i);\n return notLikeAndroid && butAndroid;\n },\n describe(ua) {\n const browser = {\n name: 'Android Browser',\n };\n const version = Utils.getFirstMatch(commonVersionIdentifier, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n\n /* PlayStation 4 */\n {\n test: [/playstation 4/i],\n describe(ua) {\n const browser = {\n name: 'PlayStation 4',\n };\n const version = Utils.getFirstMatch(commonVersionIdentifier, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n\n /* Safari */\n {\n test: [/safari|applewebkit/i],\n describe(ua) {\n const browser = {\n name: 'Safari',\n };\n const version = Utils.getFirstMatch(commonVersionIdentifier, ua);\n\n if (version) {\n browser.version = version;\n }\n\n return browser;\n },\n },\n\n /* Something else */\n {\n test: [/.*/i],\n describe(ua) {\n /* Here we try to make sure that there are explicit details about the device\n * in order to decide what regexp exactly we want to apply\n * (as there is a specific decision based on that conclusion)\n */\n const regexpWithoutDeviceSpec = /^(.*)\\/(.*) /;\n const regexpWithDeviceSpec = /^(.*)\\/(.*)[ \\t]\\((.*)/;\n const hasDeviceSpec = ua.search('\\\\(') !== -1;\n const regexp = hasDeviceSpec ? regexpWithDeviceSpec : regexpWithoutDeviceSpec;\n return {\n name: Utils.getFirstMatch(regexp, ua),\n version: Utils.getSecondMatch(regexp, ua),\n };\n },\n },\n];\n\nexport default browsersList;\n","import Utils from './utils.js';\nimport { OS_MAP } from './constants.js';\n\nexport default [\n /* Roku */\n {\n test: [/Roku\\/DVP/],\n describe(ua) {\n const version = Utils.getFirstMatch(/Roku\\/DVP-(\\d+\\.\\d+)/i, ua);\n return {\n name: OS_MAP.Roku,\n version,\n };\n },\n },\n\n /* Windows Phone */\n {\n test: [/windows phone/i],\n describe(ua) {\n const version = Utils.getFirstMatch(/windows phone (?:os)?\\s?(\\d+(\\.\\d+)*)/i, ua);\n return {\n name: OS_MAP.WindowsPhone,\n version,\n };\n },\n },\n\n /* Windows */\n {\n test: [/windows /i],\n describe(ua) {\n const version = Utils.getFirstMatch(/Windows ((NT|XP)( \\d\\d?.\\d)?)/i, ua);\n const versionName = Utils.getWindowsVersionName(version);\n\n return {\n name: OS_MAP.Windows,\n version,\n versionName,\n };\n },\n },\n\n /* Firefox on iPad */\n {\n test: [/Macintosh(.*?) FxiOS(.*?)\\//],\n describe(ua) {\n const result = {\n name: OS_MAP.iOS,\n };\n const version = Utils.getSecondMatch(/(Version\\/)(\\d[\\d.]+)/, ua);\n if (version) {\n result.version = version;\n }\n return result;\n },\n },\n\n /* macOS */\n {\n test: [/macintosh/i],\n describe(ua) {\n const version = Utils.getFirstMatch(/mac os x (\\d+(\\.?_?\\d+)+)/i, ua).replace(/[_\\s]/g, '.');\n const versionName = Utils.getMacOSVersionName(version);\n\n const os = {\n name: OS_MAP.MacOS,\n version,\n };\n if (versionName) {\n os.versionName = versionName;\n }\n return os;\n },\n },\n\n /* iOS */\n {\n test: [/(ipod|iphone|ipad)/i],\n describe(ua) {\n const version = Utils.getFirstMatch(/os (\\d+([_\\s]\\d+)*) like mac os x/i, ua).replace(/[_\\s]/g, '.');\n\n return {\n name: OS_MAP.iOS,\n version,\n };\n },\n },\n\n /* Android */\n {\n test(parser) {\n const notLikeAndroid = !parser.test(/like android/i);\n const butAndroid = parser.test(/android/i);\n return notLikeAndroid && butAndroid;\n },\n describe(ua) {\n const version = Utils.getFirstMatch(/android[\\s/-](\\d+(\\.\\d+)*)/i, ua);\n const versionName = Utils.getAndroidVersionName(version);\n const os = {\n name: OS_MAP.Android,\n version,\n };\n if (versionName) {\n os.versionName = versionName;\n }\n return os;\n },\n },\n\n /* WebOS */\n {\n test: [/(web|hpw)[o0]s/i],\n describe(ua) {\n const version = Utils.getFirstMatch(/(?:web|hpw)[o0]s\\/(\\d+(\\.\\d+)*)/i, ua);\n const os = {\n name: OS_MAP.WebOS,\n };\n\n if (version && version.length) {\n os.version = version;\n }\n return os;\n },\n },\n\n /* BlackBerry */\n {\n test: [/blackberry|\\bbb\\d+/i, /rim\\stablet/i],\n describe(ua) {\n const version = Utils.getFirstMatch(/rim\\stablet\\sos\\s(\\d+(\\.\\d+)*)/i, ua)\n || Utils.getFirstMatch(/blackberry\\d+\\/(\\d+([_\\s]\\d+)*)/i, ua)\n || Utils.getFirstMatch(/\\bbb(\\d+)/i, ua);\n\n return {\n name: OS_MAP.BlackBerry,\n version,\n };\n },\n },\n\n /* Bada */\n {\n test: [/bada/i],\n describe(ua) {\n const version = Utils.getFirstMatch(/bada\\/(\\d+(\\.\\d+)*)/i, ua);\n\n return {\n name: OS_MAP.Bada,\n version,\n };\n },\n },\n\n /* Tizen */\n {\n test: [/tizen/i],\n describe(ua) {\n const version = Utils.getFirstMatch(/tizen[/\\s](\\d+(\\.\\d+)*)/i, ua);\n\n return {\n name: OS_MAP.Tizen,\n version,\n };\n },\n },\n\n /* Linux */\n {\n test: [/linux/i],\n describe() {\n return {\n name: OS_MAP.Linux,\n };\n },\n },\n\n /* Chrome OS */\n {\n test: [/CrOS/],\n describe() {\n return {\n name: OS_MAP.ChromeOS,\n };\n },\n },\n\n /* Playstation 4 */\n {\n test: [/PlayStation 4/],\n describe(ua) {\n const version = Utils.getFirstMatch(/PlayStation 4[/\\s](\\d+(\\.\\d+)*)/i, ua);\n return {\n name: OS_MAP.PlayStation4,\n version,\n };\n },\n },\n];\n","import Utils from './utils.js';\nimport { PLATFORMS_MAP } from './constants.js';\n\n/*\n * Tablets go first since usually they have more specific\n * signs to detect.\n */\n\nexport default [\n /* Googlebot */\n {\n test: [/googlebot/i],\n describe() {\n return {\n type: 'bot',\n vendor: 'Google',\n };\n },\n },\n\n /* Huawei */\n {\n test: [/huawei/i],\n describe(ua) {\n const model = Utils.getFirstMatch(/(can-l01)/i, ua) && 'Nova';\n const platform = {\n type: PLATFORMS_MAP.mobile,\n vendor: 'Huawei',\n };\n if (model) {\n platform.model = model;\n }\n return platform;\n },\n },\n\n /* Nexus Tablet */\n {\n test: [/nexus\\s*(?:7|8|9|10).*/i],\n describe() {\n return {\n type: PLATFORMS_MAP.tablet,\n vendor: 'Nexus',\n };\n },\n },\n\n /* iPad */\n {\n test: [/ipad/i],\n describe() {\n return {\n type: PLATFORMS_MAP.tablet,\n vendor: 'Apple',\n model: 'iPad',\n };\n },\n },\n\n /* Firefox on iPad */\n {\n test: [/Macintosh(.*?) FxiOS(.*?)\\//],\n describe() {\n return {\n type: PLATFORMS_MAP.tablet,\n vendor: 'Apple',\n model: 'iPad',\n };\n },\n },\n\n /* Amazon Kindle Fire */\n {\n test: [/kftt build/i],\n describe() {\n return {\n type: PLATFORMS_MAP.tablet,\n vendor: 'Amazon',\n model: 'Kindle Fire HD 7',\n };\n },\n },\n\n /* Another Amazon Tablet with Silk */\n {\n test: [/silk/i],\n describe() {\n return {\n type: PLATFORMS_MAP.tablet,\n vendor: 'Amazon',\n };\n },\n },\n\n /* Tablet */\n {\n test: [/tablet(?! pc)/i],\n describe() {\n return {\n type: PLATFORMS_MAP.tablet,\n };\n },\n },\n\n /* iPod/iPhone */\n {\n test(parser) {\n const iDevice = parser.test(/ipod|iphone/i);\n const likeIDevice = parser.test(/like (ipod|iphone)/i);\n return iDevice && !likeIDevice;\n },\n describe(ua) {\n const model = Utils.getFirstMatch(/(ipod|iphone)/i, ua);\n return {\n type: PLATFORMS_MAP.mobile,\n vendor: 'Apple',\n model,\n };\n },\n },\n\n /* Nexus Mobile */\n {\n test: [/nexus\\s*[0-6].*/i, /galaxy nexus/i],\n describe() {\n return {\n type: PLATFORMS_MAP.mobile,\n vendor: 'Nexus',\n };\n },\n },\n\n /* Mobile */\n {\n test: [/[^-]mobi/i],\n describe() {\n return {\n type: PLATFORMS_MAP.mobile,\n };\n },\n },\n\n /* BlackBerry */\n {\n test(parser) {\n return parser.getBrowserName(true) === 'blackberry';\n },\n describe() {\n return {\n type: PLATFORMS_MAP.mobile,\n vendor: 'BlackBerry',\n };\n },\n },\n\n /* Bada */\n {\n test(parser) {\n return parser.getBrowserName(true) === 'bada';\n },\n describe() {\n return {\n type: PLATFORMS_MAP.mobile,\n };\n },\n },\n\n /* Windows Phone */\n {\n test(parser) {\n return parser.getBrowserName() === 'windows phone';\n },\n describe() {\n return {\n type: PLATFORMS_MAP.mobile,\n vendor: 'Microsoft',\n };\n },\n },\n\n /* Android Tablet */\n {\n test(parser) {\n const osMajorVersion = Number(String(parser.getOSVersion()).split('.')[0]);\n return parser.getOSName(true) === 'android' && (osMajorVersion >= 3);\n },\n describe() {\n return {\n type: PLATFORMS_MAP.tablet,\n };\n },\n },\n\n /* Android Mobile */\n {\n test(parser) {\n return parser.getOSName(true) === 'android';\n },\n describe() {\n return {\n type: PLATFORMS_MAP.mobile,\n };\n },\n },\n\n /* desktop */\n {\n test(parser) {\n return parser.getOSName(true) === 'macos';\n },\n describe() {\n return {\n type: PLATFORMS_MAP.desktop,\n vendor: 'Apple',\n };\n },\n },\n\n /* Windows */\n {\n test(parser) {\n return parser.getOSName(true) === 'windows';\n },\n describe() {\n return {\n type: PLATFORMS_MAP.desktop,\n };\n },\n },\n\n /* Linux */\n {\n test(parser) {\n return parser.getOSName(true) === 'linux';\n },\n describe() {\n return {\n type: PLATFORMS_MAP.desktop,\n };\n },\n },\n\n /* PlayStation 4 */\n {\n test(parser) {\n return parser.getOSName(true) === 'playstation 4';\n },\n describe() {\n return {\n type: PLATFORMS_MAP.tv,\n };\n },\n },\n\n /* Roku */\n {\n test(parser) {\n return parser.getOSName(true) === 'roku';\n },\n describe() {\n return {\n type: PLATFORMS_MAP.tv,\n };\n },\n },\n];\n","import Utils from './utils.js';\nimport { ENGINE_MAP } from './constants.js';\n\n/*\n * More specific goes first\n */\nexport default [\n /* EdgeHTML */\n {\n test(parser) {\n return parser.getBrowserName(true) === 'microsoft edge';\n },\n describe(ua) {\n const isBlinkBased = /\\sedg\\//i.test(ua);\n\n // return blink if it's blink-based one\n if (isBlinkBased) {\n return {\n name: ENGINE_MAP.Blink,\n };\n }\n\n // otherwise match the version and return EdgeHTML\n const version = Utils.getFirstMatch(/edge\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n return {\n name: ENGINE_MAP.EdgeHTML,\n version,\n };\n },\n },\n\n /* Trident */\n {\n test: [/trident/i],\n describe(ua) {\n const engine = {\n name: ENGINE_MAP.Trident,\n };\n\n const version = Utils.getFirstMatch(/trident\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n engine.version = version;\n }\n\n return engine;\n },\n },\n\n /* Presto */\n {\n test(parser) {\n return parser.test(/presto/i);\n },\n describe(ua) {\n const engine = {\n name: ENGINE_MAP.Presto,\n };\n\n const version = Utils.getFirstMatch(/presto\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n engine.version = version;\n }\n\n return engine;\n },\n },\n\n /* Gecko */\n {\n test(parser) {\n const isGecko = parser.test(/gecko/i);\n const likeGecko = parser.test(/like gecko/i);\n return isGecko && !likeGecko;\n },\n describe(ua) {\n const engine = {\n name: ENGINE_MAP.Gecko,\n };\n\n const version = Utils.getFirstMatch(/gecko\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n engine.version = version;\n }\n\n return engine;\n },\n },\n\n /* Blink */\n {\n test: [/(apple)?webkit\\/537\\.36/i],\n describe() {\n return {\n name: ENGINE_MAP.Blink,\n };\n },\n },\n\n /* WebKit */\n {\n test: [/(apple)?webkit/i],\n describe(ua) {\n const engine = {\n name: ENGINE_MAP.WebKit,\n };\n\n const version = Utils.getFirstMatch(/webkit\\/(\\d+(\\.?_?\\d+)+)/i, ua);\n\n if (version) {\n engine.version = version;\n }\n\n return engine;\n },\n },\n];\n","import browserParsersList from './parser-browsers.js';\nimport osParsersList from './parser-os.js';\nimport platformParsersList from './parser-platforms.js';\nimport enginesParsersList from './parser-engines.js';\nimport Utils from './utils.js';\n\n/**\n * The main class that arranges the whole parsing process.\n */\nclass Parser {\n /**\n * Create instance of Parser\n *\n * @param {String} UA User-Agent string\n * @param {Boolean} [skipParsing=false] parser can skip parsing in purpose of performance\n * improvements if you need to make a more particular parsing\n * like {@link Parser#parseBrowser} or {@link Parser#parsePlatform}\n *\n * @throw {Error} in case of empty UA String\n *\n * @constructor\n */\n constructor(UA, skipParsing = false) {\n if (UA === void (0) || UA === null || UA === '') {\n throw new Error(\"UserAgent parameter can't be empty\");\n }\n\n this._ua = UA;\n\n /**\n * @typedef ParsedResult\n * @property {Object} browser\n * @property {String|undefined} [browser.name]\n * Browser name, like `\"Chrome\"` or `\"Internet Explorer\"`\n * @property {String|undefined} [browser.version] Browser version as a String `\"12.01.45334.10\"`\n * @property {Object} os\n * @property {String|undefined} [os.name] OS name, like `\"Windows\"` or `\"macOS\"`\n * @property {String|undefined} [os.version] OS version, like `\"NT 5.1\"` or `\"10.11.1\"`\n * @property {String|undefined} [os.versionName] OS name, like `\"XP\"` or `\"High Sierra\"`\n * @property {Object} platform\n * @property {String|undefined} [platform.type]\n * platform type, can be either `\"desktop\"`, `\"tablet\"` or `\"mobile\"`\n * @property {String|undefined} [platform.vendor] Vendor of the device,\n * like `\"Apple\"` or `\"Samsung\"`\n * @property {String|undefined} [platform.model] Device model,\n * like `\"iPhone\"` or `\"Kindle Fire HD 7\"`\n * @property {Object} engine\n * @property {String|undefined} [engine.name]\n * Can be any of this: `WebKit`, `Blink`, `Gecko`, `Trident`, `Presto`, `EdgeHTML`\n * @property {String|undefined} [engine.version] String version of the engine\n */\n this.parsedResult = {};\n\n if (skipParsing !== true) {\n this.parse();\n }\n }\n\n /**\n * Get UserAgent string of current Parser instance\n * @return {String} User-Agent String of the current object\n *\n * @public\n */\n getUA() {\n return this._ua;\n }\n\n /**\n * Test a UA string for a regexp\n * @param {RegExp} regex\n * @return {Boolean}\n */\n test(regex) {\n return regex.test(this._ua);\n }\n\n /**\n * Get parsed browser object\n * @return {Object}\n */\n parseBrowser() {\n this.parsedResult.browser = {};\n\n const browserDescriptor = Utils.find(browserParsersList, (_browser) => {\n if (typeof _browser.test === 'function') {\n return _browser.test(this);\n }\n\n if (_browser.test instanceof Array) {\n return _browser.test.some(condition => this.test(condition));\n }\n\n throw new Error(\"Browser's test function is not valid\");\n });\n\n if (browserDescriptor) {\n this.parsedResult.browser = browserDescriptor.describe(this.getUA());\n }\n\n return this.parsedResult.browser;\n }\n\n /**\n * Get parsed browser object\n * @return {Object}\n *\n * @public\n */\n getBrowser() {\n if (this.parsedResult.browser) {\n return this.parsedResult.browser;\n }\n\n return this.parseBrowser();\n }\n\n /**\n * Get browser's name\n * @return {String} Browser's name or an empty string\n *\n * @public\n */\n getBrowserName(toLowerCase) {\n if (toLowerCase) {\n return String(this.getBrowser().name).toLowerCase() || '';\n }\n return this.getBrowser().name || '';\n }\n\n\n /**\n * Get browser's version\n * @return {String} version of browser\n *\n * @public\n */\n getBrowserVersion() {\n return this.getBrowser().version;\n }\n\n /**\n * Get OS\n * @return {Object}\n *\n * @example\n * this.getOS();\n * {\n * name: 'macOS',\n * version: '10.11.12'\n * }\n */\n getOS() {\n if (this.parsedResult.os) {\n return this.parsedResult.os;\n }\n\n return this.parseOS();\n }\n\n /**\n * Parse OS and save it to this.parsedResult.os\n * @return {*|{}}\n */\n parseOS() {\n this.parsedResult.os = {};\n\n const os = Utils.find(osParsersList, (_os) => {\n if (typeof _os.test === 'function') {\n return _os.test(this);\n }\n\n if (_os.test instanceof Array) {\n return _os.test.some(condition => this.test(condition));\n }\n\n throw new Error(\"Browser's test function is not valid\");\n });\n\n if (os) {\n this.parsedResult.os = os.describe(this.getUA());\n }\n\n return this.parsedResult.os;\n }\n\n /**\n * Get OS name\n * @param {Boolean} [toLowerCase] return lower-cased value\n * @return {String} name of the OS — macOS, Windows, Linux, etc.\n */\n getOSName(toLowerCase) {\n const { name } = this.getOS();\n\n if (toLowerCase) {\n return String(name).toLowerCase() || '';\n }\n\n return name || '';\n }\n\n /**\n * Get OS version\n * @return {String} full version with dots ('10.11.12', '5.6', etc)\n */\n getOSVersion() {\n return this.getOS().version;\n }\n\n /**\n * Get parsed platform\n * @return {{}}\n */\n getPlatform() {\n if (this.parsedResult.platform) {\n return this.parsedResult.platform;\n }\n\n return this.parsePlatform();\n }\n\n /**\n * Get platform name\n * @param {Boolean} [toLowerCase=false]\n * @return {*}\n */\n getPlatformType(toLowerCase = false) {\n const { type } = this.getPlatform();\n\n if (toLowerCase) {\n return String(type).toLowerCase() || '';\n }\n\n return type || '';\n }\n\n /**\n * Get parsed platform\n * @return {{}}\n */\n parsePlatform() {\n this.parsedResult.platform = {};\n\n const platform = Utils.find(platformParsersList, (_platform) => {\n if (typeof _platform.test === 'function') {\n return _platform.test(this);\n }\n\n if (_platform.test instanceof Array) {\n return _platform.test.some(condition => this.test(condition));\n }\n\n throw new Error(\"Browser's test function is not valid\");\n });\n\n if (platform) {\n this.parsedResult.platform = platform.describe(this.getUA());\n }\n\n return this.parsedResult.platform;\n }\n\n /**\n * Get parsed engine\n * @return {{}}\n */\n getEngine() {\n if (this.parsedResult.engine) {\n return this.parsedResult.engine;\n }\n\n return this.parseEngine();\n }\n\n /**\n * Get engines's name\n * @return {String} Engines's name or an empty string\n *\n * @public\n */\n getEngineName(toLowerCase) {\n if (toLowerCase) {\n return String(this.getEngine().name).toLowerCase() || '';\n }\n return this.getEngine().name || '';\n }\n\n /**\n * Get parsed platform\n * @return {{}}\n */\n parseEngine() {\n this.parsedResult.engine = {};\n\n const engine = Utils.find(enginesParsersList, (_engine) => {\n if (typeof _engine.test === 'function') {\n return _engine.test(this);\n }\n\n if (_engine.test instanceof Array) {\n return _engine.test.some(condition => this.test(condition));\n }\n\n throw new Error(\"Browser's test function is not valid\");\n });\n\n if (engine) {\n this.parsedResult.engine = engine.describe(this.getUA());\n }\n\n return this.parsedResult.engine;\n }\n\n /**\n * Parse full information about the browser\n * @returns {Parser}\n */\n parse() {\n this.parseBrowser();\n this.parseOS();\n this.parsePlatform();\n this.parseEngine();\n\n return this;\n }\n\n /**\n * Get parsed result\n * @return {ParsedResult}\n */\n getResult() {\n return Utils.assign({}, this.parsedResult);\n }\n\n /**\n * Check if parsed browser matches certain conditions\n *\n * @param {Object} checkTree It's one or two layered object,\n * which can include a platform or an OS on the first layer\n * and should have browsers specs on the bottom-laying layer\n *\n * @returns {Boolean|undefined} Whether the browser satisfies the set conditions or not.\n * Returns `undefined` when the browser is no described in the checkTree object.\n *\n * @example\n * const browser = Bowser.getParser(window.navigator.userAgent);\n * if (browser.satisfies({chrome: '>118.01.1322' }))\n * // or with os\n * if (browser.satisfies({windows: { chrome: '>118.01.1322' } }))\n * // or with platforms\n * if (browser.satisfies({desktop: { chrome: '>118.01.1322' } }))\n */\n satisfies(checkTree) {\n const platformsAndOSes = {};\n let platformsAndOSCounter = 0;\n const browsers = {};\n let browsersCounter = 0;\n\n const allDefinitions = Object.keys(checkTree);\n\n allDefinitions.forEach((key) => {\n const currentDefinition = checkTree[key];\n if (typeof currentDefinition === 'string') {\n browsers[key] = currentDefinition;\n browsersCounter += 1;\n } else if (typeof currentDefinition === 'object') {\n platformsAndOSes[key] = currentDefinition;\n platformsAndOSCounter += 1;\n }\n });\n\n if (platformsAndOSCounter > 0) {\n const platformsAndOSNames = Object.keys(platformsAndOSes);\n const OSMatchingDefinition = Utils.find(platformsAndOSNames, name => (this.isOS(name)));\n\n if (OSMatchingDefinition) {\n const osResult = this.satisfies(platformsAndOSes[OSMatchingDefinition]);\n\n if (osResult !== void 0) {\n return osResult;\n }\n }\n\n const platformMatchingDefinition = Utils.find(\n platformsAndOSNames,\n name => (this.isPlatform(name)),\n );\n if (platformMatchingDefinition) {\n const platformResult = this.satisfies(platformsAndOSes[platformMatchingDefinition]);\n\n if (platformResult !== void 0) {\n return platformResult;\n }\n }\n }\n\n if (browsersCounter > 0) {\n const browserNames = Object.keys(browsers);\n const matchingDefinition = Utils.find(browserNames, name => (this.isBrowser(name, true)));\n\n if (matchingDefinition !== void 0) {\n return this.compareVersion(browsers[matchingDefinition]);\n }\n }\n\n return undefined;\n }\n\n /**\n * Check if the browser name equals the passed string\n * @param browserName The string to compare with the browser name\n * @param [includingAlias=false] The flag showing whether alias will be included into comparison\n * @returns {boolean}\n */\n isBrowser(browserName, includingAlias = false) {\n const defaultBrowserName = this.getBrowserName().toLowerCase();\n let browserNameLower = browserName.toLowerCase();\n const alias = Utils.getBrowserTypeByAlias(browserNameLower);\n\n if (includingAlias && alias) {\n browserNameLower = alias.toLowerCase();\n }\n return browserNameLower === defaultBrowserName;\n }\n\n compareVersion(version) {\n let expectedResults = [0];\n let comparableVersion = version;\n let isLoose = false;\n\n const currentBrowserVersion = this.getBrowserVersion();\n\n if (typeof currentBrowserVersion !== 'string') {\n return void 0;\n }\n\n if (version[0] === '>' || version[0] === '<') {\n comparableVersion = version.substr(1);\n if (version[1] === '=') {\n isLoose = true;\n comparableVersion = version.substr(2);\n } else {\n expectedResults = [];\n }\n if (version[0] === '>') {\n expectedResults.push(1);\n } else {\n expectedResults.push(-1);\n }\n } else if (version[0] === '=') {\n comparableVersion = version.substr(1);\n } else if (version[0] === '~') {\n isLoose = true;\n comparableVersion = version.substr(1);\n }\n\n return expectedResults.indexOf(\n Utils.compareVersions(currentBrowserVersion, comparableVersion, isLoose),\n ) > -1;\n }\n\n isOS(osName) {\n return this.getOSName(true) === String(osName).toLowerCase();\n }\n\n isPlatform(platformType) {\n return this.getPlatformType(true) === String(platformType).toLowerCase();\n }\n\n isEngine(engineName) {\n return this.getEngineName(true) === String(engineName).toLowerCase();\n }\n\n /**\n * Is anything? Check if the browser is called \"anything\",\n * the OS called \"anything\" or the platform called \"anything\"\n * @param {String} anything\n * @param [includingAlias=false] The flag showing whether alias will be included into comparison\n * @returns {Boolean}\n */\n is(anything, includingAlias = false) {\n return this.isBrowser(anything, includingAlias) || this.isOS(anything)\n || this.isPlatform(anything);\n }\n\n /**\n * Check if any of the given values satisfies this.is(anything)\n * @param {String[]} anythings\n * @returns {Boolean}\n */\n some(anythings = []) {\n return anythings.some(anything => this.is(anything));\n }\n}\n\nexport default Parser;\n","/*!\n * Bowser - a browser detector\n * https://github.com/lancedikson/bowser\n * MIT License | (c) Dustin Diaz 2012-2015\n * MIT License | (c) Denis Demchenko 2015-2019\n */\nimport Parser from './parser.js';\nimport {\n BROWSER_MAP,\n ENGINE_MAP,\n OS_MAP,\n PLATFORMS_MAP,\n} from './constants.js';\n\n/**\n * Bowser class.\n * Keep it simple as much as it can be.\n * It's supposed to work with collections of {@link Parser} instances\n * rather then solve one-instance problems.\n * All the one-instance stuff is located in Parser class.\n *\n * @class\n * @classdesc Bowser is a static object, that provides an API to the Parsers\n * @hideconstructor\n */\nclass Bowser {\n /**\n * Creates a {@link Parser} instance\n *\n * @param {String} UA UserAgent string\n * @param {Boolean} [skipParsing=false] Will make the Parser postpone parsing until you ask it\n * explicitly. Same as `skipParsing` for {@link Parser}.\n * @returns {Parser}\n * @throws {Error} when UA is not a String\n *\n * @example\n * const parser = Bowser.getParser(window.navigator.userAgent);\n * const result = parser.getResult();\n */\n static getParser(UA, skipParsing = false) {\n if (typeof UA !== 'string') {\n throw new Error('UserAgent should be a string');\n }\n return new Parser(UA, skipParsing);\n }\n\n /**\n * Creates a {@link Parser} instance and runs {@link Parser.getResult} immediately\n *\n * @param UA\n * @return {ParsedResult}\n *\n * @example\n * const result = Bowser.parse(window.navigator.userAgent);\n */\n static parse(UA) {\n return (new Parser(UA)).getResult();\n }\n\n static get BROWSER_MAP() {\n return BROWSER_MAP;\n }\n\n static get ENGINE_MAP() {\n return ENGINE_MAP;\n }\n\n static get OS_MAP() {\n return OS_MAP;\n }\n\n static get PLATFORMS_MAP() {\n return PLATFORMS_MAP;\n }\n}\n\nexport default Bowser;\n","import Bowser from \"bowser\";\n\nexport const browser = Bowser.getParser(window.navigator.userAgent);\n\nexport const isSafari = browser && browser.satisfies({ safari: \">=0\" });\n\nexport const isFirefox = browser && browser.satisfies({ firefox: \">=0\" });\n","import { EmptyPayload } from \"@/lib/events/types\";\nimport { Step } from \"../steps/v2/step\";\nimport { AvatarMediaError } from \"./avatarManager\";\n\nexport type AvatarManagerEvents = {\n mediaTimeUpdated: number;\n stepReplayed: Step;\n stepSkipped: Step;\n expandClicked: EmptyPayload;\n mediaFinished: EmptyPayload;\n mediaPlayTriggered: EmptyPayload;\n mediaPlayed: EmptyPayload;\n mediaPaused: EmptyPayload;\n mediaPauseTriggered: EmptyPayload;\n mediaTrackerInitialized: EmptyPayload;\n skipClicked: EmptyPayload;\n dismissClicked: EmptyPayload;\n mediaSeeked: { seekedTo: number };\n currentSectionSet: EmptyPayload;\n captionClicked: { status: boolean };\n muteClicked: { status: boolean };\n minimizeClicked: EmptyPayload;\n playClicked: EmptyPayload;\n pauseClicked: EmptyPayload;\n replayClicked: EmptyPayload;\n mediaError: AvatarMediaError;\n};\n\nexport type AvatarEventContext = {\n time: number;\n sectionIndex: number;\n avatarStatus: string;\n};\n\nexport const AvatarNamespace = \"avatar\" as const;\n","import { AllContexts, AllEvents } from \"./allEvents\";\nimport { BaseEventEmitter } from \"./baseEventEmitter\";\nimport { globalEventBus, GlobalEventBus } from \"./eventBus\";\nimport { EventsWithContext } from \"./types\";\n\nexport class EventEmitter<\n Namespace extends string,\n Events extends Record,\n Context = any,\n> extends BaseEventEmitter {\n private globalEventBus: GlobalEventBus;\n private namespace: Namespace;\n\n constructor(namespace: Namespace) {\n super();\n this.globalEventBus = globalEventBus;\n this.namespace = namespace;\n }\n\n emit(\n type: Key,\n eventData: Events[Key],\n context?: Context,\n options = { skipGlobal: false }\n ): EventsWithContext[Key] {\n const eventWithProcessedContext = super.emit(type, eventData, context);\n\n const namespacedType = `${this.namespace}.${String(type)}` as `${Namespace}.${Key & string}`;\n\n if (!options.skipGlobal) {\n this.globalEventBus.emit(\n namespacedType as any,\n eventWithProcessedContext.payload,\n eventWithProcessedContext.context as AllContexts\n );\n }\n\n return eventWithProcessedContext;\n }\n}\n","import { autorun, makeAutoObservable, runInAction } from \"mobx\";\nimport { AvatarStateStorage } from \"../persistent-storage/avatarState\";\nimport { Section } from \"./types\";\nimport { Step } from \"../steps/v2/step\";\nimport { createAvatarActor, createAvatarStream } from \"./avatarManager.fsm\";\nimport { isSafari } from \"@/lib/browser\";\nimport { AvatarEventContext, AvatarManagerEvents, AvatarNamespace } from \"./avatarManager.events\";\nimport { EventEmitter } from \"@/lib/events/eventEmitter\";\nimport invariant from \"ts-invariant\";\n\nexport type SectionMedia = {\n sectionId: string;\n mediaUrl: string;\n mediaDuration: number;\n};\n\nexport type AvatarMediaError = {\n mediaSource: \"current\" | \"next\";\n code: number;\n message: string;\n};\n\ntype SectionId = string;\ntype ObjectUrl = string;\n\nexport type SectionMediaUrls = Record;\nexport type MediaCache = Record;\n\nexport interface AvatarManagerParams {\n sectionMedias: SectionMedia[];\n sytemFlowMediaUrls: SectionMediaUrls;\n skipBlobMediaPreload?: boolean;\n playbackRate?: number;\n stateStorage: AvatarStateStorage;\n mediaAmplificationRate?: number;\n highlightPlayButtonEnabled?: boolean;\n showWatermark?: boolean;\n}\n\nexport class AvatarManager {\n private mediaElement: HTMLMediaElement | null = null;\n\n private audioContext: AudioContext | null = null;\n private mediaSourceNodes: Map = new Map();\n private gainNode: GainNode | null = null;\n\n currentTime: number = 0;\n passedTimeOffset: number = 0;\n totalMediaDuration: number = 0;\n playbackRate: number;\n mediaAmplificationRate?: number;\n\n isMuted: boolean = false;\n isProgressVisible: boolean = true;\n isCaptionsVisible: boolean = true;\n isInitializing: boolean = true;\n isBuffering: boolean = false;\n initializedAt: number = 0;\n\n currentSection?: Section;\n currentStep?: Step;\n\n private stateStorage: AvatarStateStorage;\n private sectionMedias: SectionMedia[] = [];\n private sytemFlowMediaUrls: SectionMediaUrls = {};\n private mediaCache: MediaCache = {};\n private skipBlobMediaPreload?: boolean;\n private mediaTimeTrackerStopFn?: () => void;\n private isSystemMediaPreloaded = false;\n private highlightPlayButtonEnabled = false;\n private showWatermark = false;\n\n private bufferingCheckIntervalId: ReturnType | null = null;\n private readonly bufferingCheckInterval = 200;\n private bufferingCheckState = {\n lastPlayPos: 0,\n };\n\n events = new EventEmitter(AvatarNamespace);\n\n machine: ReturnType;\n machineStream: ReturnType;\n\n constructor({\n sectionMedias,\n stateStorage,\n sytemFlowMediaUrls: systemFlowMedias,\n skipBlobMediaPreload,\n playbackRate,\n mediaAmplificationRate,\n highlightPlayButtonEnabled,\n showWatermark,\n }: AvatarManagerParams) {\n makeAutoObservable(this);\n this.stateStorage = stateStorage;\n this.sectionMedias = sectionMedias;\n this.sytemFlowMediaUrls = systemFlowMedias;\n this.totalMediaDuration = sectionMedias.reduce((acc, section) => acc + section.mediaDuration, 0);\n this.skipBlobMediaPreload = skipBlobMediaPreload;\n this.playbackRate = playbackRate ?? 1;\n this.mediaAmplificationRate = mediaAmplificationRate;\n this.highlightPlayButtonEnabled = highlightPlayButtonEnabled ?? false;\n this.showWatermark = showWatermark ?? false;\n this.initializedAt = Date.now();\n\n const initialState = this.stateStorage.get();\n this.isCaptionsVisible = initialState.isCaptionsVisible;\n this.isMuted = initialState.isMuted;\n\n if (this.shouldAmplifyMedia) {\n this.setupMediaAmplification();\n }\n\n autorun(() => {\n this.stateStorage.set({\n isCaptionsVisible: this.isCaptionsVisible,\n isMuted: this.isMuted,\n });\n });\n\n this.machine = createAvatarActor({\n hooks: {\n onPlayMedia: this.playMedia.bind(this),\n onPauseMedia: this.pauseMedia.bind(this),\n onAutoPlayMedia: this.tryAutoPlayMedia.bind(this),\n onReplayStep: this.handleReplayStep.bind(this),\n onSkipStep: this.handleSkipStep.bind(this),\n onFinishMedia: this.handleFinishMedia.bind(this),\n onSyncMediaElementCurrentTime: this.handleSyncMediaElementCurrentTime.bind(this),\n },\n });\n this.machineStream = createAvatarStream(this.machine);\n this.machine.start();\n }\n\n setCurrentSection(\n section: Section,\n step: Step,\n options: { currentTime?: number; autoPlay: boolean; isProgressRingVisible: boolean }\n ) {\n this.currentSection = section;\n this.currentStep = step;\n this.isProgressVisible = options.isProgressRingVisible;\n\n const currentTime = options?.currentTime ?? 0;\n this.setCurrentTime(currentTime);\n this.bufferingCheckState.lastPlayPos = currentTime;\n\n this.updatePassedTimeOffset(section.id);\n\n this.machine.send({ type: \"sectionTransition\", section, step, playSettings: { autoPlay: options.autoPlay } });\n\n this.initMediaTimeTracker();\n }\n\n setCurrentStep(step: Step) {\n this.machine.send({ type: \"stepTransition\", step });\n }\n\n onMediaElementChanged(el: HTMLMediaElement) {\n this.mediaElement = el;\n\n this.setupBufferingCheck();\n\n this.mediaElement.playbackRate = this.playbackRate;\n if (this.shouldAmplifyMedia) {\n this.amplifyMedia(this.mediaElement);\n }\n this.machine.send({ type: \"mediaElementInitialized\" });\n }\n\n setupBufferingCheck() {\n if (this.bufferingCheckIntervalId) clearInterval(this.bufferingCheckIntervalId);\n this.bufferingCheckIntervalId = setInterval(this.isMediaBuffering.bind(this), this.bufferingCheckInterval);\n }\n\n handleReplayStep(step: Step) {\n this.events.emit(\"stepReplayed\", step);\n }\n\n handleSkipStep(step: Step) {\n this.events.emit(\"stepSkipped\", step);\n }\n\n handleSyncMediaElementCurrentTime(time: number) {\n if (!this.mediaElement) return;\n if (time === this.mediaElement.currentTime * 1000) return;\n this.seekMedia(time);\n }\n\n play() {\n this.machine.send({ type: \"systemPlay\" });\n }\n\n private playMedia() {\n this.mediaElement?.play();\n this.events.emit(\"mediaPlayTriggered\", {}, this.buildEventContext());\n }\n\n async tryAutoPlayMedia() {\n await this.mediaElement?.play();\n this.events.emit(\"mediaPlayTriggered\", {}, this.buildEventContext());\n }\n\n pause() {\n this.machine.send({ type: \"systemPause\" });\n }\n\n private pauseMedia() {\n this.mediaElement?.pause();\n this.events.emit(\"mediaPauseTriggered\", {}, this.buildEventContext());\n }\n\n onPlayClicked() {\n this.events.emit(\"playClicked\", {}, this.buildEventContext());\n this.machine.send({ type: \"playClicked\" });\n }\n\n onPauseClicked() {\n this.events.emit(\"pauseClicked\", {}, this.buildEventContext());\n this.machine.send({ type: \"pauseClicked\" });\n }\n\n onReplayClicked() {\n this.events.emit(\"replayClicked\", {}, this.buildEventContext());\n this.machine.send({ type: \"replayClicked\" });\n }\n\n onSkipClicked() {\n this.events.emit(\"skipClicked\", {}, this.buildEventContext());\n this.machine.send({ type: \"skipClicked\" });\n }\n\n get isControlsAlwaysVisible() {\n return this.isAutoPlayFailed || this.isPausedForDisabledAutoPlay;\n }\n\n get cantPlay() {\n return (\n this.isAutoPlayFailed ||\n this.isPausedForDisabledAutoPlay ||\n (this.currentStep?.isAtom && this.currentStep?.isBlocking)\n );\n }\n\n get isAutoPlayFailed() {\n return this.state!.hasTag(\"autoPlayFailed\");\n }\n\n get canPlay() {\n return this.state!.can({ type: \"playClicked\" });\n }\n\n get canPause() {\n return this.state!.can({ type: \"pauseClicked\" });\n }\n\n get canSkip() {\n return this.state!.can({ type: \"skipClicked\" });\n }\n\n get canReplay() {\n return this.state!.can({ type: \"replayClicked\" });\n }\n\n get isMinimized() {\n return this.state?.hasTag(\"minimized\");\n }\n\n get isPlaying() {\n return this.state?.matches({ running: \"playing\" });\n }\n\n get progress() {\n if (this.totalMediaDuration === 0) return 0;\n if (!this.context) return 0;\n\n return ((this.passedTimeOffset + this.currentTime) / this.totalMediaDuration) * 100;\n }\n\n get currentMediaDuration() {\n return this.context?.section?.mediaDuration ?? 0;\n }\n\n onMediaPlay() {\n this.machine.send({ type: \"mediaPlaying\" });\n this.events.emit(\"mediaPlayed\", {}, this.buildEventContext());\n }\n\n onMediaCanPlay() {\n this.isInitializing = false;\n this.machine.send({ type: \"mediaCanPlay\" });\n }\n\n onMediaError(error: AvatarMediaError) {\n this.events.emit(\"mediaError\", error, this.buildEventContext());\n }\n\n onMediaCanPlayThrough() {\n if (this.isSystemMediaPreloaded) return;\n this.isSystemMediaPreloaded = true;\n this.preloadSystemFlowMedia();\n }\n\n onMediaPaused() {\n this.machine.send({ type: \"mediaPaused\" });\n this.events.emit(\"mediaPaused\", {}, this.buildEventContext());\n }\n\n handleFinishMedia() {\n this.events.emit(\"mediaFinished\", {}, this.buildEventContext());\n }\n\n onMediaFinished() {\n this.setCurrentTime(this.currentMediaDuration);\n this.machine.send({ type: \"mediaFinished\" });\n this.events.emit(\"mediaFinished\", {}, this.buildEventContext());\n }\n\n onMuteChanged(isMuted: boolean) {\n this.isMuted = isMuted;\n this.events.emit(\"muteClicked\", { status: isMuted }, this.buildEventContext());\n }\n\n onShowCaptionsChanged(shouldShowCaptions: boolean) {\n this.isCaptionsVisible = shouldShowCaptions;\n this.events.emit(\"captionClicked\", { status: shouldShowCaptions }, this.buildEventContext());\n }\n\n onMinimizeClicked() {\n this.events.emit(\"minimizeClicked\", {}, this.buildEventContext());\n }\n\n onExpandClicked() {\n this.events.emit(\"expandClicked\", {}, this.buildEventContext());\n }\n\n onDismissClicked() {\n this.machine.send({ type: \"dismissClicked\" });\n this.events.emit(\"dismissClicked\", {}, this.buildEventContext());\n }\n\n minimize() {\n this.machine.send({ type: \"minimize\" });\n }\n\n expand() {\n this.machine.send({ type: \"expand\" });\n }\n\n terminate() {\n this.machine.send({ type: \"terminate\" });\n this.mediaTimeTrackerStopFn?.();\n if (this.bufferingCheckIntervalId) clearInterval(this.bufferingCheckIntervalId);\n this.audioContext?.close();\n }\n\n get status() {\n return this.machineStream.current?.value;\n }\n\n updatePassedTimeOffset(sectionId: string) {\n const section = this.sectionMedias.find((s) => s.sectionId === sectionId);\n if (!section) return;\n const sectionIndex = this.sectionMedias.indexOf(section);\n const passedTime = this.sectionMedias.slice(0, sectionIndex).reduce((acc, s) => acc + s.mediaDuration, 0);\n this.passedTimeOffset = passedTime;\n }\n\n seekMediaToEnd() {\n this.seekMedia(this.currentMediaDuration);\n }\n\n seekMedia(to: number) {\n runInAction(() => {\n if (this.mediaElement) {\n this.pause();\n\n if (isSafari) {\n this.mediaElement.load(); // Required for Safari\n }\n this.mediaElement.currentTime = to / 1000;\n this.setCurrentTime(to);\n this.events.emit(\"mediaTimeUpdated\", to, this.buildEventContext(), { skipGlobal: true });\n this.events.emit(\"mediaSeeked\", { seekedTo: to }, this.buildEventContext(), { skipGlobal: true });\n }\n });\n }\n\n get nextSectionMediaUrl() {\n if (!this.currentSection) return \"\";\n\n const currentSectionIndex = this.currentSection.index;\n const nextSection = this.sectionMedias.find(\n (s) => s.sectionId === this.sectionMedias[currentSectionIndex + 1]?.sectionId\n );\n return nextSection?.mediaUrl;\n }\n\n get originalMediaUrl() {\n if (!this.currentSection) return \"\";\n return this.currentSection.avatarMediaUrl;\n }\n\n get mediaUrl(): string {\n if (!this.currentSection) return \"\";\n\n if (this.mediaCache[this.currentSection.id]) {\n return this.mediaCache[this.currentSection.id];\n }\n\n return this.currentSection.avatarMediaUrl;\n }\n\n get state() {\n return this.machineStream.current;\n }\n\n get context() {\n return this.machineStream.current?.context;\n }\n\n get isPausedForDisabledAutoPlay() {\n return this.state?.hasTag(\"pausedForDisabledAutoPlay\");\n }\n\n get shouldHighlightPlayButton() {\n return this.highlightPlayButtonEnabled && this.isPausedForDisabledAutoPlay;\n }\n\n get shouldShowWatermark() {\n return this.showWatermark;\n }\n\n toggleInitializing() {\n this.isInitializing = !this.isInitializing;\n }\n\n private setCurrentTime(time: number) {\n runInAction(() => {\n this.currentTime = time;\n this.events.emit(\"mediaTimeUpdated\", time, this.buildEventContext(), { skipGlobal: true });\n this.machine.send({ type: \"timeUpdate\", currentTime: time });\n });\n }\n\n private initMediaTimeTracker() {\n this.mediaTimeTrackerStopFn?.();\n this.mediaTimeTrackerStopFn = undefined;\n\n this.mediaTimeTrackerStopFn = autorun(() => {\n const updateTime = () => {\n if (!this.mediaElement || !this.isPlaying) return;\n this.setCurrentTime(this.mediaElement.currentTime * 1000);\n requestAnimationFrame(updateTime.bind(this));\n };\n\n if (this.isPlaying) {\n updateTime();\n }\n });\n\n this.events.emit(\"mediaTrackerInitialized\", {}, this.buildEventContext());\n }\n\n private preloadSystemFlowMedia() {\n if (this.skipBlobMediaPreload) {\n return;\n }\n\n Object.entries(this.sytemFlowMediaUrls).forEach(([sectionId, mediaUrl]) => {\n const isMediaAlreadyServed = this.mediaUrl === mediaUrl;\n if (isMediaAlreadyServed) {\n return;\n }\n\n if (mediaUrl.length > 0 && mediaUrl.indexOf(\"https\") === 0) {\n fetch(mediaUrl)\n .then((res) => res.blob())\n .then((blob) => {\n this.mediaCache[sectionId] = URL.createObjectURL(blob);\n })\n .catch((err) => {\n console.error(err);\n });\n }\n });\n }\n\n private isMediaBuffering() {\n if (!this.mediaElement) return;\n\n const currentPlayPos = this.currentTime;\n\n // Offset is used to provide a small tolerance for playback position changes\n // It allows for minor fluctuations in playback without triggering buffering detection\n const offset = (this.bufferingCheckInterval - 20) / 1000;\n\n const isPlaybackPositionAdvanced = currentPlayPos > this.bufferingCheckState.lastPlayPos + offset;\n const isPlaybackPositionStalled = currentPlayPos <= this.bufferingCheckState.lastPlayPos + offset;\n const isMediaNotReadyToPlay = this.mediaElement.readyState < 2;\n\n if ((!this.isBuffering && isPlaybackPositionStalled && this.isPlaying) || isMediaNotReadyToPlay) {\n this.isBuffering = true;\n }\n\n if ((this.isBuffering && isPlaybackPositionAdvanced && this.isPlaying) || this.cantPlay) {\n this.isBuffering = false;\n }\n\n this.bufferingCheckState.lastPlayPos = currentPlayPos;\n }\n\n get shouldAmplifyMedia() {\n return !!this.mediaAmplificationRate && !isSafari;\n }\n\n private setupMediaAmplification() {\n invariant(!!this.mediaAmplificationRate, \"mediaAmplificationRate is not set\");\n\n this.audioContext = new AudioContext();\n this.gainNode = this.audioContext.createGain();\n this.gainNode.gain.value = this.mediaAmplificationRate!;\n this.gainNode!.connect(this.audioContext.destination);\n }\n\n private amplifyMedia(mediaElement: HTMLMediaElement) {\n invariant(!!this.audioContext, \"audioContext is not initialized\");\n invariant(!!this.gainNode, \"gainNode is not initialized\");\n\n if (!this.mediaSourceNodes.has(mediaElement)) {\n const mediaSourceNode = this.audioContext!.createMediaElementSource(mediaElement);\n mediaSourceNode.connect(this.gainNode!);\n this.mediaSourceNodes.set(mediaElement, mediaSourceNode);\n }\n }\n\n private buildEventContext(): AvatarEventContext {\n return {\n time: this.currentTime,\n sectionIndex: this.currentSection?.index ?? -1,\n avatarStatus: this.state?.value ? JSON.stringify(this.state.value) : \"\",\n };\n }\n}\n","import { autorun, runInAction } from \"mobx\";\nimport { TourPlaybackManager } from \".\";\n\nexport class StepActionsFacade {\n private tourPlaybackManager: TourPlaybackManager;\n\n constructor(tourPlaybackManager: TourPlaybackManager) {\n this.tourPlaybackManager = tourPlaybackManager;\n }\n\n proceedNext() {\n this.tourPlaybackManager.handleProceedNextFromStep();\n }\n\n onStepOnTrackChanged(stepId: string, callback: (isOnTrack: boolean) => void): () => void {\n return autorun(() => {\n const isOnTrack = this.tourPlaybackManager.isStepOnTrack(stepId);\n runInAction(() => {\n callback(isOnTrack);\n });\n });\n }\n\n onTargetElementChange(stepId: string, callback: (el: Element | null) => void): () => void {\n return autorun(() => {\n const element = this.tourPlaybackManager.getTargetElement(stepId);\n runInAction(() => {\n callback(element);\n });\n });\n }\n\n setCurrentTargetElement(el?: Element | null) {\n this.tourPlaybackManager.setCurrentTargetElement(el);\n }\n\n suspendTour() {\n this.tourPlaybackManager.suspendTour(\"userAction\");\n }\n\n loadLastCheckpoint() {\n this.tourPlaybackManager.loadLastCheckpoint();\n }\n\n finishTour() {\n this.tourPlaybackManager.finishTour();\n }\n\n switchTour(guideId: string) {\n this.tourPlaybackManager.switchTour(guideId);\n }\n\n // To prevent circular reference in JSON.stringify\n toJSON() {\n return null;\n }\n}\n\nexport class FlowHookActionsFacade {\n private tourPlaybackManager: TourPlaybackManager;\n\n constructor(tourPlaybackManager: TourPlaybackManager) {\n this.tourPlaybackManager = tourPlaybackManager;\n }\n\n finishTour() {\n this.tourPlaybackManager.finishTour();\n }\n\n loadLastCheckpoint() {\n this.tourPlaybackManager.loadLastCheckpoint();\n }\n\n // To prevent circular reference in JSON.stringify\n toJSON() {\n return null;\n }\n}\n","import { TourPlayback } from \"@common/schemas\";\nimport { QuestionChoice } from \"@common/schemas/v2\";\nimport * as schemas from \"@common/schemas\";\n\nexport type FlowFinishHookType = \"loadCheckpoint\" | \"finishTour\";\nexport type FlowHookType = FlowFinishHookType;\n\nexport type FlowHooks = {\n onFinish?: FlowFinishHookType;\n};\n\nexport type FlowOptions = {\n isAvatarProgressRingVisible: boolean;\n};\n\nexport const systemFlowTypes = [\"unsuspend\", \"targetNotFound\", \"wanderingOff\"] as const;\nexport type SystemFlowType = (typeof systemFlowTypes)[number];\nexport type SystemFlows = Record;\nexport type FlowKey = SystemFlowType | \"tour\";\n\ntype Flow = {\n key: FlowKey;\n sections: TourPlayback[\"sections\"];\n hooks?: FlowHooks;\n options: FlowOptions;\n};\n\nexport interface UnsuspendFlowParams {\n resumeTour: schemas.Fillers[\"resumeTour\"];\n}\n\nexport interface WanderingOffFlowParams {\n targetLost: schemas.Fillers[\"targetLost\"];\n resumeTour: schemas.Fillers[\"resumeTour\"];\n}\n\nexport interface TargetNotFoundFlowParams {\n targetNotFound: schemas.Fillers[\"targetNotFound\"];\n}\n\nexport interface CreateSystemFlowsParams {\n unsuspendFlow: UnsuspendFlowParams;\n targetNotFoundFlow: TargetNotFoundFlowParams;\n wanderingOffFlow: WanderingOffFlowParams;\n}\n\nexport const createFlows = (\n tourPlayback: TourPlayback,\n systemFlowParams: CreateSystemFlowsParams\n): Record => {\n return {\n tour: createTourFlow(tourPlayback),\n ...createSystemFlows(systemFlowParams),\n };\n};\n\nexport const createSystemFlows = ({\n unsuspendFlow,\n targetNotFoundFlow,\n wanderingOffFlow,\n}: CreateSystemFlowsParams): SystemFlows => {\n return {\n unsuspend: createUnsuspendFlow(unsuspendFlow),\n targetNotFound: createTargetNotFoundFlow(targetNotFoundFlow),\n wanderingOff: buildWanderingOffFlow({\n targetLost: wanderingOffFlow.targetLost,\n resumeTour: wanderingOffFlow.resumeTour,\n }),\n };\n};\n\nexport const createTourFlow = (tourPlayback: TourPlayback): Flow => {\n return {\n key: \"tour\",\n sections: tourPlayback.sections,\n hooks: { onFinish: \"finishTour\" },\n options: {\n isAvatarProgressRingVisible: true,\n },\n };\n};\n\nconst createUnsuspendFlow = (params: UnsuspendFlowParams): Flow => {\n return {\n key: \"unsuspend\",\n sections: [\n {\n id: \"unsuspend\",\n mediaDuration: params.resumeTour!.mediaDuration!,\n avatarMediaUrl: params.resumeTour!.videoUrl!,\n text: \"\",\n transcript: [],\n steps: [\n {\n id: \"resumeTour\",\n start: 0,\n end: params.resumeTour!.mediaDuration!,\n text: \"\",\n attributes: {\n isCheckpoint: false,\n type: \"filler\",\n },\n },\n ],\n },\n ],\n hooks: {\n onFinish: \"loadCheckpoint\",\n },\n options: {\n isAvatarProgressRingVisible: false,\n },\n };\n};\n\nconst createTargetNotFoundFlow = (params: TargetNotFoundFlowParams): Flow => {\n const targetNotFoundQuestionChoices: QuestionChoice[] = [\n {\n id: \"restart\",\n type: \"proceedNext\",\n text: params.targetNotFound!.restartButtonText!,\n },\n ];\n\n if (params.targetNotFound!.contactSupportUrl) {\n targetNotFoundQuestionChoices.push({\n id: \"contactSupport\",\n type: \"contactSupport\",\n text: params.targetNotFound!.contactSupportButtonText!,\n url: params.targetNotFound!.contactSupportUrl,\n });\n }\n\n return {\n key: \"targetNotFound\",\n sections: [\n {\n id: \"targetNotFound\",\n mediaDuration: params.targetNotFound!.mediaDuration!,\n avatarMediaUrl: params.targetNotFound!.videoUrl!,\n text: \"\",\n transcript: [],\n steps: [\n {\n id: \"targetNotFound\",\n text: \"\",\n start: 0,\n end: params.targetNotFound!.mediaDuration!,\n attributes: {\n isCheckpoint: false,\n type: \"question\",\n questionType: \"multipleChoice\",\n choices: targetNotFoundQuestionChoices,\n title: params.targetNotFound!.title!,\n text: params.targetNotFound!.content!,\n },\n },\n ],\n },\n ],\n hooks: {\n onFinish: \"loadCheckpoint\",\n },\n options: {\n isAvatarProgressRingVisible: false,\n },\n };\n};\n\nconst buildWanderingOffFlow = (params: WanderingOffFlowParams): Flow => {\n return {\n key: \"wanderingOff\",\n sections: [\n {\n id: \"wanderingOff\",\n mediaDuration: params.targetLost!.mediaDuration!,\n avatarMediaUrl: params.targetLost!.videoUrl!,\n text: \"\",\n transcript: [],\n steps: [\n {\n id: \"wanderingOffQuestion\",\n text: \"\",\n start: 0,\n end: params.targetLost!.mediaDuration!,\n attributes: {\n isCheckpoint: false,\n type: \"question\",\n questionType: \"multipleChoice\",\n choices: [\n {\n id: \"resume\",\n type: \"proceedNext\",\n text: params.targetLost!.resumeTourButtonText!,\n },\n {\n id: \"later\",\n type: \"suspendTour\",\n text: params.targetLost!.laterButtonText!,\n },\n ],\n title: params.targetLost!.title!,\n text: params.targetLost!.content!,\n },\n },\n ],\n },\n {\n id: \"resumeTour\",\n mediaDuration: params.resumeTour!.mediaDuration!,\n avatarMediaUrl: params.resumeTour!.videoUrl!,\n text: \"\",\n transcript: [],\n steps: [\n {\n id: \"resumeTour\",\n start: 0,\n end: params.resumeTour!.mediaDuration!,\n text: \"\",\n attributes: {\n isCheckpoint: false,\n type: \"filler\",\n },\n },\n ],\n },\n ],\n hooks: {\n onFinish: \"loadCheckpoint\",\n },\n options: {\n isAvatarProgressRingVisible: false,\n },\n };\n};\n","import validate from './validate.js';\n\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nvar byteToHex = [];\nfor (var i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n //\n // Note to future-self: No, you can't remove the `toLowerCase()` call.\n // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351\n return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n var uuid = unsafeStringify(arr, offset);\n // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexport default stringify;","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\n\nvar getRandomValues;\nvar rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n return getRandomValues(rnds8);\n}","var randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nexport default {\n randomUUID\n};","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n options = options || {};\n var rnds = options.random || (options.rng || rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n offset = offset || 0;\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return unsafeStringify(rnds);\n}\nexport default v4;","var util;\n(function (util) {\n util.assertEqual = (val) => val;\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array\n .map((val) => (typeof val === \"string\" ? `'${val}'` : val))\n .join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nvar objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nconst ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nconst getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then &&\n typeof data.then === \"function\" &&\n data.catch &&\n typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n\nconst ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nconst quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nclass ZodError extends Error {\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n get errors() {\n return this.issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `smaller than or equal to`\n : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\n\nlet overrideErrorMap = errorMap;\nfunction setErrorMap(map) {\n overrideErrorMap = map;\n}\nfunction getErrorMap() {\n return overrideErrorMap;\n}\n\nconst makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nconst EMPTY_PATH = [];\nfunction addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n overrideMap,\n overrideMap === errorMap ? undefined : errorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nclass ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" &&\n (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nconst INVALID = Object.freeze({\n status: \"aborted\",\n});\nconst DIRTY = (value) => ({ status: \"dirty\", value });\nconst OK = (value) => ({ status: \"valid\", value });\nconst isAborted = (x) => x.status === \"aborted\";\nconst isDirty = (x) => x.status === \"dirty\";\nconst isValid = (x) => x.status === \"valid\";\nconst isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\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\nfunction __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nfunction __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nvar errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message === null || message === void 0 ? void 0 : message.message;\n})(errorUtil || (errorUtil = {}));\n\nvar _ZodEnum_cache, _ZodNativeEnum_cache;\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (this._key instanceof Array) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n var _a, _b;\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message !== null && message !== void 0 ? message : ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nclass ZodType {\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n }\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n var _a;\n const ctx = {\n common: {\n issues: [],\n async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n async: true,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult)\n ? maybeAsyncResult\n : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\"\n ? refinementData(val, ctx)\n : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this, this._def);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n // let regex = `\\\\d{2}:\\\\d{2}:\\\\d{2}`;\n let regex = `([01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d`;\n if (args.precision) {\n regex = `${regex}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n regex = `${regex}(\\\\.\\\\d+)?`;\n }\n return regex;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nfunction datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nclass ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch (_a) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n var _a, _b;\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,\n local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options === null || options === void 0 ? void 0 : options.position,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * @deprecated Use z.string().min(1) instead.\n * @see {@link ZodString.min}\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n var _a;\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / Math.pow(10, decCount);\n}\nclass ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" ||\n (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null, min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" ||\n ch.kind === \"int\" ||\n ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = BigInt(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n var _a;\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\nclass ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nclass ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nclass ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nclass ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nclass ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nclass ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nclass ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nclass ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nclass ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nclass ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n return (this._cached = { shape, keys });\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever &&\n this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") ;\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n var _a, _b, _c, _d;\n const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // (def: Def) =>\n // (\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge(\n // merging: Incoming\n // ): //ZodObject = (merging) => {\n // ZodObject<\n // extendShape>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n util.objectKeys(mask).forEach((key) => {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nclass ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nclass ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util\n .objectKeys(a)\n .filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date &&\n bType === ZodParsedType.date &&\n +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nclass ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\nclass ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nclass ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nclass ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nclass ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nclass ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args\n .parseAsync(args, params)\n .catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args\n ? args\n : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nclass ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nclass ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nclass ZodEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodEnum_cache.set(this, void 0);\n }\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\").has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\n_ZodEnum_cache = new WeakMap();\nZodEnum.create = createZodEnum;\nclass ZodNativeEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodNativeEnum_cache.set(this, void 0);\n }\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string &&\n ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\").has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\n_ZodNativeEnum_cache = new WeakMap();\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nclass ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise &&\n ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise\n ? ctx.data\n : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nclass ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return base;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((base) => {\n if (!isValid(base))\n return base;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nclass ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nclass ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nclass ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\"\n ? params.default\n : () => params.default,\n ...processCreateParams(params),\n });\n};\nclass ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nclass ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nconst BRAND = Symbol(\"zod_brand\");\nclass ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nclass ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nclass ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n if (isValid(result)) {\n result.value = Object.freeze(result.value);\n }\n return result;\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\nfunction custom(check, params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n var _a, _b;\n if (!check(data)) {\n const p = typeof params === \"function\"\n ? params(data)\n : typeof params === \"string\"\n ? { message: params }\n : params;\n const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n ctx.addIssue({ code: \"custom\", ...p2, fatal: _fatal });\n }\n });\n return ZodAny.create();\n}\nconst late = {\n object: ZodObject.lazycreate,\n};\nvar ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\nconst instanceOfType = (\n// const instanceOfType = any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nconst coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nconst NEVER = INVALID;\n\nvar z = /*#__PURE__*/Object.freeze({\n __proto__: null,\n defaultErrorMap: errorMap,\n setErrorMap: setErrorMap,\n getErrorMap: getErrorMap,\n makeIssue: makeIssue,\n EMPTY_PATH: EMPTY_PATH,\n addIssueToContext: addIssueToContext,\n ParseStatus: ParseStatus,\n INVALID: INVALID,\n DIRTY: DIRTY,\n OK: OK,\n isAborted: isAborted,\n isDirty: isDirty,\n isValid: isValid,\n isAsync: isAsync,\n get util () { return util; },\n get objectUtil () { return objectUtil; },\n ZodParsedType: ZodParsedType,\n getParsedType: getParsedType,\n ZodType: ZodType,\n datetimeRegex: datetimeRegex,\n ZodString: ZodString,\n ZodNumber: ZodNumber,\n ZodBigInt: ZodBigInt,\n ZodBoolean: ZodBoolean,\n ZodDate: ZodDate,\n ZodSymbol: ZodSymbol,\n ZodUndefined: ZodUndefined,\n ZodNull: ZodNull,\n ZodAny: ZodAny,\n ZodUnknown: ZodUnknown,\n ZodNever: ZodNever,\n ZodVoid: ZodVoid,\n ZodArray: ZodArray,\n ZodObject: ZodObject,\n ZodUnion: ZodUnion,\n ZodDiscriminatedUnion: ZodDiscriminatedUnion,\n ZodIntersection: ZodIntersection,\n ZodTuple: ZodTuple,\n ZodRecord: ZodRecord,\n ZodMap: ZodMap,\n ZodSet: ZodSet,\n ZodFunction: ZodFunction,\n ZodLazy: ZodLazy,\n ZodLiteral: ZodLiteral,\n ZodEnum: ZodEnum,\n ZodNativeEnum: ZodNativeEnum,\n ZodPromise: ZodPromise,\n ZodEffects: ZodEffects,\n ZodTransformer: ZodEffects,\n ZodOptional: ZodOptional,\n ZodNullable: ZodNullable,\n ZodDefault: ZodDefault,\n ZodCatch: ZodCatch,\n ZodNaN: ZodNaN,\n BRAND: BRAND,\n ZodBranded: ZodBranded,\n ZodPipeline: ZodPipeline,\n ZodReadonly: ZodReadonly,\n custom: custom,\n Schema: ZodType,\n ZodSchema: ZodType,\n late: late,\n get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },\n coerce: coerce,\n any: anyType,\n array: arrayType,\n bigint: bigIntType,\n boolean: booleanType,\n date: dateType,\n discriminatedUnion: discriminatedUnionType,\n effect: effectsType,\n 'enum': enumType,\n 'function': functionType,\n 'instanceof': instanceOfType,\n intersection: intersectionType,\n lazy: lazyType,\n literal: literalType,\n map: mapType,\n nan: nanType,\n nativeEnum: nativeEnumType,\n never: neverType,\n 'null': nullType,\n nullable: nullableType,\n number: numberType,\n object: objectType,\n oboolean: oboolean,\n onumber: onumber,\n optional: optionalType,\n ostring: ostring,\n pipeline: pipelineType,\n preprocess: preprocessType,\n promise: promiseType,\n record: recordType,\n set: setType,\n strictObject: strictObjectType,\n string: stringType,\n symbol: symbolType,\n transformer: effectsType,\n tuple: tupleType,\n 'undefined': undefinedType,\n union: unionType,\n unknown: unknownType,\n 'void': voidType,\n NEVER: NEVER,\n ZodIssueCode: ZodIssueCode,\n quotelessJson: quotelessJson,\n ZodError: ZodError\n});\n\nexport { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodReadonly, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodSymbol, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, datetimeRegex, z as default, errorMap as defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void, z };\n","import { z } from \"zod\";\nconst TextBlockSchema = z.object({\n id: z.string(),\n type: z.literal(\"text\"),\n text: z.string(),\n});\nconst ImgBlockSchema = z.object({\n id: z.string(),\n type: z.literal(\"img\"),\n src: z.string(),\n width: z.string().optional(),\n});\nconst VideoBlockSchema = z.object({\n id: z.string(),\n type: z.literal(\"video\"),\n src: z.string(),\n autoplay: z.boolean().optional(),\n loop: z.boolean().optional(),\n});\nexport const BlockSchema = z.discriminatedUnion(\"type\", [TextBlockSchema, ImgBlockSchema, VideoBlockSchema]);\nexport function getAssetUrls(blocks) {\n if (!blocks)\n return [];\n const mediaUrls = [];\n for (const block of blocks) {\n if (block.type === \"text\")\n continue;\n switch (block.type) {\n case \"img\":\n mediaUrls.push({ src: block.src, type: \"image\" });\n break;\n case \"video\":\n mediaUrls.push({ src: block.src, type: \"video\" });\n break;\n }\n }\n return mediaUrls;\n}\n","import { v4 as uuidv4 } from \"uuid\";\nimport { getAssetUrls } from \"../../schemas/form/html-content\";\nexport class Step {\n id;\n text;\n start;\n end;\n attributes;\n createdAt;\n constructor(step) {\n this.id = step.id;\n this.text = step.text;\n this.start = step.start;\n this.end = step.end;\n this.attributes = StepAttributesFactory.create(step.attributes);\n this.createdAt = step.createdAt;\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n start: this.start,\n end: this.end,\n attributes: this.attributes.toJSON(),\n createdAt: this.createdAt,\n };\n }\n}\nexport class StepAttributesFactory {\n static getClass(type) {\n const map = {\n filler: FillerStepAttributes,\n userClick: UserClickStepAttributes,\n highlight: HighlightStepAttributes,\n question: MultipleChoiceQuestionStepAttributes,\n modal: MultipleChoiceModalStepAttributes,\n showContent: ShowContentStepAttributes,\n waitForElement: WaitForElementStepAttributes,\n redirect: RedirectStepAttributes,\n autoType: AutoTypeStepAttributes,\n autoClick: AutoClickStepAttributes,\n sleep: SleepStepAttributes,\n drag: DragStepAttributes,\n };\n const StepClass = map[type];\n if (!StepClass) {\n throw new Error(`Unknown step attributes type: ${type.type}`);\n }\n return StepClass;\n }\n static create(attributes) {\n const StepClass = this.getClass(attributes.type);\n return new StepClass(attributes);\n }\n static createWithFormDefaults(attributes) {\n const StepClass = this.getClass(attributes.type);\n return StepClass.createWithFormDefaults(attributes);\n }\n}\nconst stepTypes = [\n \"filler\",\n \"userClick\",\n \"highlight\",\n \"question\",\n \"modal\",\n \"showContent\",\n \"waitForElement\",\n \"redirect\",\n \"autoType\",\n \"autoClick\",\n \"drag\",\n \"sleep\",\n];\nexport function isValidStepType(type) {\n return stepTypes.includes(type);\n}\nexport class OnTrackCondition {\n id;\n left_operand;\n right_operand;\n operator;\n isManaged;\n isCarried;\n isModified;\n carriedFrom;\n constructor(condition) {\n this.id = condition.id ?? uuidv4();\n this.left_operand = condition.left_operand || \"selector\";\n this.operator = condition.operator || (this.left_operand === \"selector\" ? \"exists\" : \"contains\");\n this.right_operand = condition.right_operand || \"\";\n this.isManaged = condition.isManaged ?? false;\n this.isCarried = condition.isCarried ?? false;\n this.isModified = condition.isModified ?? false;\n this.carriedFrom = condition.carriedFrom;\n }\n isEqual(condition) {\n return (this.left_operand === condition.left_operand &&\n this.right_operand === condition.right_operand &&\n this.operator === condition.operator);\n }\n isEmpty() {\n return !this.operator || !this.right_operand || this.right_operand.length === 0;\n }\n isUrlCondition() {\n return this.left_operand === \"url\";\n }\n isSelectorCondition() {\n return this.left_operand === \"selector\";\n }\n isSupplementarySelectorCondition() {\n return this.isSelectorCondition() && !this.isManaged;\n }\n isTargetSelectorCondition() {\n return this.isSelectorCondition() && this.isManaged;\n }\n isCarriedSelectorCondition() {\n return this.isSelectorCondition() && this.isCarried;\n }\n static empty(leftOperand) {\n return new OnTrackCondition({\n left_operand: leftOperand,\n });\n }\n toJSON() {\n return {\n id: this.id,\n left_operand: this.left_operand,\n operator: this.operator,\n right_operand: this.right_operand,\n isManaged: this.isManaged,\n isCarried: this.isCarried,\n isModified: this.isModified,\n };\n }\n}\nexport class OnTrackConditions {\n isEnabled;\n conditions;\n constructor(conditions) {\n this.isEnabled = conditions.isEnabled;\n this.conditions = conditions.conditions.map((condition) => new OnTrackCondition(condition));\n }\n get nonEmptyConditions() {\n return this.conditions.filter((condition) => !condition.isEmpty());\n }\n get urlCondition() {\n return this.conditions.find((condition) => condition.isUrlCondition());\n }\n get urlConditions() {\n return this.conditions.filter((condition) => condition.isUrlCondition());\n }\n get nonEmptyUrlConditions() {\n return this.urlConditions.filter((condition) => !condition.isEmpty());\n }\n get selectorConditions() {\n return this.conditions.filter((condition) => condition.isSelectorCondition());\n }\n get nonEmptySelectorConditions() {\n return this.selectorConditions.filter((condition) => !condition.isEmpty());\n }\n get selectors() {\n return this.nonEmptySelectorConditions.map((condition) => condition.right_operand);\n }\n isEmpty() {\n return this.conditions.every((condition) => condition.isEmpty());\n }\n toJSON() {\n return {\n isEnabled: this.isEnabled,\n conditions: this.conditions.map((condition) => condition.toJSON()),\n };\n }\n}\n// Assumes max one managed condition exists\nexport const partitionManagedOnTrackConditions = (conditions) => {\n if (conditions.length === 0) {\n return [[], []];\n }\n const managedConditionIndex = conditions.findIndex((condition) => condition.isManaged);\n const managedCondition = managedConditionIndex !== -1 ? conditions[managedConditionIndex] : undefined;\n if (!managedCondition) {\n return [[], conditions];\n }\n const rest = conditions.slice(0, managedConditionIndex).concat(conditions.slice(managedConditionIndex + 1));\n return [[managedCondition], rest];\n};\nconst buildOnTrackConditionsWithTargetElementSelector = (selector, defaultValue) => {\n if (selector && selector.length > 0) {\n const emptyUrlCondition = OnTrackCondition.empty(\"url\");\n const existingUrlCondition = defaultValue.urlCondition;\n const backfillUnmarkedManagedCondition = (conditions) => {\n const newConditions = [];\n const selectorConditions = conditions.filter((condition) => condition.isSelectorCondition());\n const supplementarySelectorConditions = selectorConditions.filter((condition) => condition.isSupplementarySelectorCondition());\n const unmarkedManagedConditionIndex = supplementarySelectorConditions.findIndex((condition) => condition.right_operand === selector);\n const isAnySupplementarySelectorConditionContainsTargetElementSelector = unmarkedManagedConditionIndex !== -1;\n if (!isAnySupplementarySelectorConditionContainsTargetElementSelector) {\n const targetElementSelectorCondition = new OnTrackCondition({\n left_operand: \"selector\",\n right_operand: selector,\n operator: \"exists\",\n isManaged: true,\n isCarried: false,\n isModified: false,\n });\n newConditions.push(targetElementSelectorCondition);\n }\n else {\n supplementarySelectorConditions[unmarkedManagedConditionIndex].isManaged = true;\n }\n newConditions.push(...supplementarySelectorConditions);\n return newConditions;\n };\n const conditions = [\n existingUrlCondition ?? emptyUrlCondition,\n ...backfillUnmarkedManagedCondition(defaultValue.conditions),\n ];\n return new OnTrackConditions({\n isEnabled: true,\n conditions: conditions,\n });\n }\n return defaultValue;\n};\nexport class BaseStepAttributes {\n isCheckpoint;\n onTrackConditions;\n constructor(attributes) {\n this.isCheckpoint = attributes.isCheckpoint ?? true;\n const defaultOnTrackConditions = {\n isEnabled: false,\n conditions: [],\n };\n this.onTrackConditions = new OnTrackConditions(attributes.onTrackConditions ?? defaultOnTrackConditions);\n }\n isTargetable() {\n return false;\n }\n isHighlightable() {\n return false;\n }\n assetUrls = () => [];\n toJSON() {\n return {\n isCheckpoint: this.isCheckpoint,\n onTrackConditions: this.onTrackConditions.toJSON(),\n };\n }\n}\nexport class FillerStepAttributes extends BaseStepAttributes {\n type = \"filler\";\n constructor(attributes) {\n super(attributes);\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"filler\",\n });\n }\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n };\n }\n}\nexport class RedirectStepAttributes extends BaseStepAttributes {\n type = \"redirect\";\n slug;\n applyConditionsOnNextSteps;\n changeType;\n constructor(attributes) {\n super(attributes);\n this.slug = attributes.slug;\n this.applyConditionsOnNextSteps = attributes.applyConditionsOnNextSteps;\n this.changeType = attributes.changeType || \"redirect\";\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"redirect\",\n });\n }\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n slug: this.slug,\n applyConditionsOnNextSteps: this.applyConditionsOnNextSteps,\n changeType: this.changeType,\n };\n }\n}\nexport class DragStepAttributes extends BaseStepAttributes {\n type = \"drag\";\n direction;\n targetElementSelector;\n targetScreenshot;\n targetRoute;\n targetElementHighlightStyle;\n virtualCursor;\n constructor(attributes) {\n super(attributes);\n this.direction = attributes.direction;\n this.targetElementSelector = attributes.targetElementSelector;\n this.targetScreenshot = attributes.targetScreenshot;\n this.targetRoute = attributes.targetRoute;\n this.targetElementHighlightStyle = \"pulsingBorder\";\n this.virtualCursor = new VirtualCursorSettings(attributes.virtualCursor || { animationType: \"drag\" });\n // this.onTrackConditions = buildOnTrackConditionsWithTargetElementSelector(\n // this.targetElementSelector,\n // this.onTrackConditions\n // );\n }\n isTargetable() {\n return true;\n }\n isHighlightable() {\n return true;\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"drag\",\n direction: attributes.direction ?? \"up\",\n targetElementSelector: attributes.targetElementSelector ?? \"\",\n });\n }\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n direction: this.direction,\n targetRoute: this.targetRoute,\n targetScreenshot: this.targetScreenshot,\n targetElementSelector: this.targetElementSelector,\n targetElementHighlightStyle: this.targetElementHighlightStyle,\n virtualCursor: this.virtualCursor.toJSON(),\n };\n }\n}\nexport class UserClickStepAttributes extends BaseStepAttributes {\n type = \"userClick\";\n targetElementSelector;\n targetScreenshot;\n targetRoute;\n targetElementHighlightStyle;\n virtualCursor;\n additionalContent;\n additionalContentState;\n clickDetectionMethod;\n constructor(attributes) {\n super(attributes);\n this.targetElementSelector = attributes.targetElementSelector;\n this.targetScreenshot = attributes.targetScreenshot;\n this.targetRoute = attributes.targetRoute;\n this.targetElementHighlightStyle = attributes.targetElementHighlightStyle || \"pulsingBorder\";\n this.virtualCursor = new VirtualCursorSettings(attributes.virtualCursor || { animationType: \"move\" });\n this.additionalContent = attributes.additionalContent;\n this.additionalContentState = attributes.additionalContentState;\n // this.onTrackConditions = buildOnTrackConditionsWithTargetElementSelector(\n // this.targetElementSelector,\n // this.onTrackConditions\n // );\n this.clickDetectionMethod = attributes.clickDetectionMethod || \"click\";\n }\n isTargetable() {\n return true;\n }\n isHighlightable() {\n return true;\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"userClick\",\n targetElementSelector: attributes.targetElementSelector ?? \"\",\n clickDetectionMethod: attributes.clickDetectionMethod ?? \"click\",\n });\n }\n assetUrls = () => getAssetUrls(this.additionalContentState);\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n targetRoute: this.targetRoute,\n targetScreenshot: this.targetScreenshot,\n targetElementSelector: this.targetElementSelector,\n targetElementHighlightStyle: this.targetElementHighlightStyle,\n virtualCursor: this.virtualCursor.toJSON(),\n additionalContent: this.additionalContent,\n additionalContentState: this.additionalContentState,\n clickDetectionMethod: this.clickDetectionMethod,\n };\n }\n}\nexport class HighlightStepAttributes extends BaseStepAttributes {\n type = \"highlight\";\n targetElementSelector;\n targetScreenshot;\n targetRoute;\n targetElementHighlightStyle;\n virtualCursor;\n additionalContent;\n additionalContentState;\n constructor(attributes) {\n super(attributes);\n this.targetElementSelector = attributes.targetElementSelector;\n this.targetScreenshot = attributes.targetScreenshot;\n this.targetRoute = attributes.targetRoute;\n this.targetElementHighlightStyle = attributes.targetElementHighlightStyle || \"backdrop\";\n this.virtualCursor = new VirtualCursorSettings(attributes.virtualCursor || { animationType: \"hidden\" });\n this.additionalContent = attributes.additionalContent;\n this.additionalContentState = attributes.additionalContentState;\n // this.onTrackConditions = buildOnTrackConditionsWithTargetElementSelector(\n // this.targetElementSelector,\n // this.onTrackConditions\n // );\n }\n isTargetable() {\n return true;\n }\n isHighlightable() {\n return true;\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"highlight\",\n targetElementSelector: attributes.targetElementSelector ?? \"\",\n });\n }\n assetUrls = () => getAssetUrls(this.additionalContentState);\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n targetRoute: this.targetRoute,\n targetScreenshot: this.targetScreenshot,\n targetElementSelector: this.targetElementSelector,\n targetElementHighlightStyle: this.targetElementHighlightStyle,\n virtualCursor: this.virtualCursor.toJSON(),\n additionalContent: this.additionalContent,\n additionalContentState: this.additionalContentState,\n };\n }\n}\nexport class ShowContentStepAttributes extends BaseStepAttributes {\n type = \"showContent\";\n content;\n contentState;\n constructor(attributes) {\n super(attributes);\n this.content = attributes.content;\n this.contentState = attributes.contentState;\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"showContent\",\n content: attributes.content ?? \"\",\n });\n }\n assetUrls = () => getAssetUrls(this.contentState);\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n content: this.content,\n contentState: this.contentState,\n };\n }\n}\nexport class WaitForElementStepAttributes extends BaseStepAttributes {\n type = \"waitForElement\";\n targetElementSelector;\n targetScreenshot;\n targetRoute;\n timeout;\n constructor(attributes) {\n super(attributes);\n this.targetElementSelector = attributes.targetElementSelector;\n this.targetScreenshot = attributes.targetScreenshot;\n this.targetRoute = attributes.targetRoute;\n this.type = attributes.type;\n this.timeout = attributes.timeout ?? 6000;\n // this.onTrackConditions = buildOnTrackConditionsWithTargetElementSelector(\n // this.targetElementSelector,\n // this.onTrackConditions\n // );\n }\n isTargetable() {\n return true;\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"waitForElement\",\n targetElementSelector: attributes.targetElementSelector ?? \"\",\n });\n }\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n targetRoute: this.targetRoute,\n targetScreenshot: this.targetScreenshot,\n targetElementSelector: this.targetElementSelector,\n timeout: this.timeout,\n onTrackConditions: this.onTrackConditions.toJSON(),\n };\n }\n}\nexport class SleepStepAttributes extends BaseStepAttributes {\n type = \"sleep\";\n duration;\n constructor(attributes) {\n super(attributes);\n this.duration = attributes.duration;\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"sleep\",\n duration: attributes.duration ?? 0,\n });\n }\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n duration: this.duration,\n };\n }\n}\nexport class VirtualCursorSettings {\n animationType;\n constructor(settings) {\n this.animationType = settings?.animationType ?? \"move\";\n }\n toJSON() {\n return {\n animationType: this.animationType,\n };\n }\n}\nexport class MultipleChoiceQuestionStepAttributes extends BaseStepAttributes {\n type = \"question\";\n questionType = \"multipleChoice\";\n choices;\n title;\n text;\n additionalContent;\n additionalContentState;\n constructor(attributes) {\n super(attributes);\n this.choices = QuestionChoiceFactory.createList(attributes.choices);\n this.text = attributes.text;\n this.title = attributes.title;\n this.additionalContent = attributes.additionalContent;\n this.additionalContentState = attributes.additionalContentState;\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"question\",\n questionType: \"multipleChoice\",\n choices: attributes.choices ?? [],\n title: attributes.title ?? \"\",\n });\n }\n assetUrls = () => getAssetUrls(this.additionalContentState);\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n questionType: this.questionType,\n choices: this.choices.map((choice) => choice.toJSON()),\n title: this.title,\n text: this.text,\n additionalContent: this.additionalContent,\n additionalContentState: this.additionalContentState,\n };\n }\n}\nexport class QuestionChoiceFactory {\n static create(choice) {\n switch (choice.type) {\n case \"link\":\n return new LinkChoice(choice);\n case \"proceedNext\":\n return new ProceedNextChoice(choice);\n case \"suspendTour\":\n return new SuspendTourChoice(choice);\n case \"finishTour\":\n return new FinishTourChoice(choice);\n case \"switchTour\":\n return new SwitchTourChoice(choice);\n case \"triggerClick\":\n return new TriggerClickChoice(choice);\n case \"contactSupport\":\n return new ContactSupportChoice(choice);\n case \"loadCheckpoint\":\n return new LoadCheckpointChoice(choice);\n default:\n throw new Error(`Unknown question choice type: ${choice.type}`);\n }\n }\n static createList(choices) {\n if (!choices) {\n return [];\n }\n return choices.map((choice) => QuestionChoiceFactory.create(choice));\n }\n}\nexport class LinkChoice {\n type = \"link\";\n id;\n text;\n url;\n buttonVariant;\n windowType;\n constructor(choice) {\n this.id = choice.id;\n this.text = choice.text;\n this.url = choice.url;\n this.windowType = choice.windowType || \"newTab\";\n this.buttonVariant = choice.buttonVariant || \"primary\";\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"link\",\n id: attributes.id ?? uuidv4(),\n text: attributes.text ?? \"\",\n url: attributes.url ?? \"\",\n });\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n type: this.type,\n url: this.url,\n windowType: this.windowType,\n buttonVariant: this.buttonVariant,\n };\n }\n}\nexport class ProceedNextChoice {\n type = \"proceedNext\";\n id;\n text;\n buttonVariant;\n constructor(choice) {\n this.id = choice.id;\n this.text = choice.text;\n this.buttonVariant = choice.buttonVariant || \"primary\";\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"proceedNext\",\n id: attributes.id ?? uuidv4(),\n text: attributes.text ?? \"\",\n });\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n type: this.type,\n buttonVariant: this.buttonVariant,\n };\n }\n}\nexport class SuspendTourChoice {\n type = \"suspendTour\";\n id;\n text;\n buttonVariant;\n constructor(choice) {\n this.id = choice.id;\n this.text = choice.text;\n this.buttonVariant = choice.buttonVariant || \"primary\";\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"suspendTour\",\n id: attributes.id ?? uuidv4(),\n text: attributes.text ?? \"\",\n });\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n type: this.type,\n buttonVariant: this.buttonVariant,\n };\n }\n}\nexport class FinishTourChoice {\n type = \"finishTour\";\n id;\n text;\n buttonVariant;\n constructor(choice) {\n this.id = choice.id;\n this.text = choice.text;\n this.buttonVariant = choice.buttonVariant || \"primary\";\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"finishTour\",\n id: attributes.id ?? uuidv4(),\n text: attributes.text ?? \"\",\n });\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n type: this.type,\n buttonVariant: this.buttonVariant,\n };\n }\n}\nexport class SwitchTourChoice {\n type = \"switchTour\";\n id;\n text;\n buttonVariant;\n guideId;\n constructor(choice) {\n this.id = choice.id;\n this.text = choice.text;\n this.buttonVariant = choice.buttonVariant || \"primary\";\n this.guideId = choice.guideId;\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"switchTour\",\n id: attributes.id ?? uuidv4(),\n text: attributes.text ?? \"\",\n guideId: attributes.guideId ?? \"\",\n });\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n type: this.type,\n buttonVariant: this.buttonVariant,\n guideId: this.guideId,\n };\n }\n}\nexport class TriggerClickChoice {\n type = \"triggerClick\";\n id;\n text;\n selector;\n buttonVariant;\n constructor(choice) {\n this.id = choice.id;\n this.text = choice.text;\n this.selector = choice.selector;\n this.buttonVariant = choice.buttonVariant || \"primary\";\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"triggerClick\",\n id: attributes.id ?? uuidv4(),\n text: attributes.text ?? \"\",\n selector: attributes.selector ?? \"\",\n });\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n type: this.type,\n selector: this.selector,\n buttonVariant: this.buttonVariant,\n };\n }\n}\nexport class ContactSupportChoice {\n type = \"contactSupport\";\n id;\n text;\n url;\n buttonVariant;\n constructor(choice) {\n this.id = choice.id;\n this.text = choice.text;\n this.url = choice.url;\n this.buttonVariant = choice.buttonVariant || \"primary\";\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"contactSupport\",\n id: attributes.id ?? uuidv4(),\n text: attributes.text ?? \"\",\n url: attributes.url ?? \"\",\n });\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n type: this.type,\n url: this.url,\n buttonVariant: this.buttonVariant,\n };\n }\n}\nexport class LoadCheckpointChoice {\n type = \"loadCheckpoint\";\n id;\n text;\n buttonVariant;\n constructor(choice) {\n this.id = choice.id;\n this.text = choice.text;\n this.buttonVariant = choice.buttonVariant || \"primary\";\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"loadCheckpoint\",\n id: attributes.id ?? uuidv4(),\n text: attributes.text ?? \"\",\n });\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n type: this.type,\n buttonVariant: this.buttonVariant,\n };\n }\n}\nexport class FinishTourModalChoice {\n type = \"finishTour\";\n id;\n text;\n buttonVariant;\n constructor(option) {\n this.id = option.id;\n this.text = option.text;\n this.buttonVariant = option.buttonVariant || \"primary\";\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"finishTour\",\n id: attributes.id ?? uuidv4(),\n text: attributes.text ?? \"\",\n });\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n type: this.type,\n buttonVariant: this.buttonVariant,\n };\n }\n}\nexport class ProceedNextModalChoice {\n type = \"proceedNext\";\n id;\n text;\n buttonVariant;\n constructor(option) {\n this.id = option.id;\n this.text = option.text;\n this.buttonVariant = option.buttonVariant || \"primary\";\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"proceedNext\",\n id: attributes.id ?? uuidv4(),\n text: attributes.text ?? \"\",\n });\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n type: this.type,\n buttonVariant: this.buttonVariant,\n };\n }\n}\nexport class ContactSupportModalChoice {\n type = \"contactSupport\";\n id;\n text;\n buttonVariant;\n url;\n constructor(option) {\n this.id = option.id;\n this.text = option.text;\n this.url = option.url;\n this.buttonVariant = option.buttonVariant || \"primary\";\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"contactSupport\",\n id: attributes.id ?? uuidv4(),\n text: attributes.text ?? \"\",\n url: attributes.url ?? \"\",\n });\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n type: this.type,\n url: this.url,\n buttonVariant: this.buttonVariant,\n };\n }\n}\nexport class LinkModalChoice {\n type = \"link\";\n id;\n text;\n url;\n buttonVariant;\n windowType;\n constructor(option) {\n this.id = option.id;\n this.text = option.text;\n this.url = option.url;\n this.windowType = option.windowType || \"newTab\";\n this.buttonVariant = option.buttonVariant || \"primary\";\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"link\",\n id: attributes.id ?? uuidv4(),\n text: attributes.text ?? \"\",\n url: attributes.url ?? \"\",\n });\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n type: this.type,\n url: this.url,\n windowType: this.windowType,\n buttonVariant: this.buttonVariant,\n };\n }\n}\nexport class SwitchTourModalChoice {\n type = \"switchTour\";\n id;\n text;\n guideId;\n buttonVariant;\n constructor(option) {\n this.id = option.id;\n this.text = option.text;\n this.guideId = option.guideId;\n this.buttonVariant = option.buttonVariant || \"primary\";\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"switchTour\",\n id: attributes.id ?? uuidv4(),\n text: attributes.text ?? \"\",\n guideId: attributes.guideId ?? \"\",\n });\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n type: this.type,\n guideId: this.guideId,\n buttonVariant: this.buttonVariant,\n };\n }\n}\nexport class SuspendTourModalChoice {\n type = \"suspendTour\";\n id;\n text;\n buttonVariant;\n constructor(option) {\n this.id = option.id;\n this.text = option.text;\n this.buttonVariant = option.buttonVariant || \"primary\";\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"suspendTour\",\n id: attributes.id ?? uuidv4(),\n text: attributes.text ?? \"\",\n });\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n type: this.type,\n buttonVariant: this.buttonVariant,\n };\n }\n}\nexport class TriggerClickModalChoice {\n type = \"triggerClick\";\n id;\n text;\n selector;\n buttonVariant;\n constructor(choice) {\n this.id = choice.id;\n this.text = choice.text;\n this.selector = choice.selector;\n this.buttonVariant = choice.buttonVariant || \"primary\";\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"triggerClick\",\n id: attributes.id ?? uuidv4(),\n text: attributes.text ?? \"\",\n selector: attributes.selector ?? \"\",\n });\n }\n toJSON() {\n return {\n id: this.id,\n text: this.text,\n type: this.type,\n selector: this.selector,\n buttonVariant: this.buttonVariant,\n };\n }\n}\nexport class ModalChoiceFactory {\n static create(option) {\n switch (option.type) {\n case \"finishTour\":\n return new FinishTourModalChoice(option);\n case \"proceedNext\":\n return new ProceedNextModalChoice(option);\n case \"link\":\n return new LinkModalChoice(option);\n case \"contactSupport\":\n return new ContactSupportModalChoice(option);\n case \"switchTour\":\n return new SwitchTourModalChoice(option);\n case \"suspendTour\":\n return new SuspendTourModalChoice(option);\n case \"triggerClick\":\n return new TriggerClickModalChoice(option);\n default:\n throw new Error(`Unknown question choice type: ${option.type}`);\n }\n }\n static createList(options) {\n if (!options) {\n return [];\n }\n return options.map((opt) => ModalChoiceFactory.create(opt));\n }\n}\nexport class MultipleChoiceModalStepAttributes extends BaseStepAttributes {\n type = \"modal\";\n questionType;\n choices;\n title;\n description;\n modalContent;\n modalContentState;\n variant;\n constructor(attributes) {\n super(attributes);\n this.questionType = \"multipleChoice\";\n this.choices = ModalChoiceFactory.createList(attributes.choices);\n this.title = attributes.title;\n this.description = attributes.description;\n this.modalContent = attributes.modalContent;\n this.modalContentState = attributes.modalContentState;\n this.variant = attributes.variant;\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"modal\",\n questionType: \"multipleChoice\",\n title: attributes.title ?? \"\",\n modalContent: attributes.modalContent ?? \"\",\n choices: attributes.choices ?? [],\n });\n }\n assetUrls = () => getAssetUrls(this.modalContentState);\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n questionType: this.questionType,\n choices: this.choices.map((choice) => choice.toJSON()),\n title: this.title,\n description: this.description,\n modalContent: this.modalContent,\n modalContentState: this.modalContentState,\n variant: this.variant,\n };\n }\n}\nexport class AutoTypeStepAttributes extends BaseStepAttributes {\n type = \"autoType\";\n targetElementSelector;\n targetScreenshot;\n targetRoute;\n instantPaste;\n targetElementHighlightStyle;\n text;\n constructor(attributes) {\n super(attributes);\n this.targetElementSelector = attributes.targetElementSelector ?? \"\";\n this.targetScreenshot = attributes.targetScreenshot;\n this.targetRoute = attributes.targetRoute;\n this.targetElementHighlightStyle = attributes.targetElementHighlightStyle || \"pulsingPoint\";\n this.text = attributes.text;\n this.instantPaste = attributes.instantPaste || false;\n // this.onTrackConditions = buildOnTrackConditionsWithTargetElementSelector(\n // this.targetElementSelector,\n // this.onTrackConditions\n // );\n }\n isTargetable() {\n return true;\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"autoType\",\n text: attributes.text ?? \"\",\n targetElementSelector: attributes.targetElementSelector ?? \"\",\n });\n }\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n targetRoute: this.targetRoute,\n targetScreenshot: this.targetScreenshot,\n targetElementSelector: this.targetElementSelector,\n targetElementHighlightStyle: this.targetElementHighlightStyle,\n text: this.text,\n instantPaste: this.instantPaste,\n onTrackConditions: this.onTrackConditions.toJSON(),\n };\n }\n}\nexport class AutoClickStepAttributes extends BaseStepAttributes {\n type = \"autoClick\";\n targetElementSelector;\n targetScreenshot;\n targetRoute;\n targetElementHighlightStyle;\n virtualCursor;\n constructor(attributes) {\n super(attributes);\n this.targetElementSelector = attributes.targetElementSelector;\n this.targetScreenshot = attributes.targetScreenshot;\n this.targetRoute = attributes.targetRoute;\n this.virtualCursor = new VirtualCursorSettings(attributes.virtualCursor);\n this.targetElementHighlightStyle = attributes.targetElementHighlightStyle || \"pulsingPoint\";\n // this.onTrackConditions = buildOnTrackConditionsWithTargetElementSelector(\n // this.targetElementSelector,\n // this.onTrackConditions\n // );\n }\n isTargetable() {\n return true;\n }\n static createWithFormDefaults(attributes) {\n return new this({\n ...attributes,\n type: \"autoClick\",\n targetElementSelector: attributes.targetElementSelector ?? \"\",\n });\n }\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n targetRoute: this.targetRoute,\n targetScreenshot: this.targetScreenshot,\n targetElementSelector: this.targetElementSelector,\n targetElementHighlightStyle: this.targetElementHighlightStyle,\n onTrackConditions: this.onTrackConditions.toJSON(),\n };\n }\n}\n","import { BaseEventEmitter } from \"./baseEventEmitter\";\n\nexport class SimpleEventEmitter> extends BaseEventEmitter {\n constructor() {\n super();\n }\n}\n","import type * as schemas from \"@common/schemas/v2\";\nimport * as models from \"@common/models/v2\";\nimport { StepActions } from \"./step\";\nimport { SimpleEventEmitter } from \"@/lib/events/simpleEventEmitter\";\nimport { EmptyPayload } from \"@/lib/events/types\";\nimport { QuestionChoice } from \"./question\";\nimport { ModalChoice } from \"./modal\";\nimport { FlowFlexibility } from \"@common/schemas\";\nimport { computed, makeObservable, observable, reaction, runInAction } from \"mobx\";\n\nexport type StepEvents = {\n initialized: EmptyPayload;\n started: EmptyPayload;\n finished: EmptyPayload;\n disposed: EmptyPayload;\n ran: EmptyPayload;\n questionAnswered: { choice: QuestionChoice };\n modalAnswered: { choice: ModalChoice };\n};\n\nexport class BaseStep {\n id: string;\n text: string;\n start: number;\n end: number;\n attributes: models.StepAttributes;\n createdAt?: string;\n actions: StepActions;\n events: SimpleEventEmitter = new SimpleEventEmitter();\n flowFlexibility: FlowFlexibility;\n isOnTrack = false;\n isProceededNext = false;\n isFinished = false;\n stopWatchingOnTrack?: () => void;\n stopProceedNextWhenUnblocked?: () => void;\n\n constructor(step: schemas.Step, actions: StepActions, flowFlexibility: FlowFlexibility) {\n this.id = step.id;\n this.text = step.text;\n this.start = step.start;\n this.end = step.end;\n this.attributes = models.StepAttributesFactory.create(step.attributes);\n this.createdAt = step.createdAt;\n this.actions = actions;\n this.flowFlexibility = flowFlexibility;\n makeObservable(this, {\n isBlocking: computed,\n isOnTrack: observable,\n isFinished: observable,\n });\n }\n\n async init() {\n runInAction(() => {\n this.isFinished = false;\n this.isProceededNext = false;\n });\n\n this.events.emit(\"initialized\", {});\n this.proceedNextWhenUnblocked();\n this.stopWatchingOnTrack?.();\n this.stopWatchingOnTrack = this.actions.onStepOnTrackChanged(this.id, (isOnTrack) => {\n runInAction(() => {\n this.isOnTrack = isOnTrack;\n });\n });\n }\n\n async run() {\n this.events.emit(\"ran\", {});\n }\n\n async finish() {\n this.events.emit(\"finished\", {});\n runInAction(() => {\n this.isFinished = true;\n });\n }\n\n private proceedNextWhenUnblocked() {\n this.stopProceedNextWhenUnblocked = reaction(\n () => [this.isBlocking, this.isFinished, this.isOnTrack],\n ([isBlocking, isFinishAchieved, isOnTrack]) => {\n if (!isBlocking && isOnTrack && (isFinishAchieved || this.skipStepOnEarlyUnblock)) {\n this.actions.proceedNext();\n this.stopProceedNextWhenUnblocked?.();\n }\n }\n );\n }\n\n dispose() {\n this.events.emit(\"disposed\", {});\n this.stopWatchingOnTrack?.();\n this.stopProceedNextWhenUnblocked?.();\n }\n\n get additionalContent(): string | undefined {\n return undefined;\n }\n\n get prompt(): any {\n return null;\n }\n\n get isBlocking(): boolean {\n return this.isBlockingStepType && !this.isOnTrack;\n }\n\n get skipStepOnEarlyUnblock(): boolean {\n return false;\n }\n\n get isBlockingStepType(): boolean {\n return this.flowFlexibility === \"strict\";\n }\n\n get isTargetableStepType(): boolean {\n return false;\n }\n\n get isBlockingAndTargetableStepType(): boolean {\n return this.isBlockingStepType && this.isTargetableStepType;\n }\n\n get isAtom(): boolean {\n return this.start === this.end;\n }\n\n get assetUrls() {\n return this.attributes.assetUrls();\n }\n\n get emitter() {\n return this.events;\n }\n\n toJSON() {\n return null;\n }\n}\n","export class Deferred {\n promise: Promise;\n resolve: Function = (value: T) => {};\n reject: Function = (reason?: any) => {};\n\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\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 != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nmodule.exports = freeGlobal;\n","var freeGlobal = require('./_freeGlobal');\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\nmodule.exports = root;\n","var root = require('./_root');\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\nmodule.exports = now;\n","/** Used to match a single whitespace character. */\nvar reWhitespace = /\\s/;\n\n/**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\nfunction trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n}\n\nmodule.exports = trimmedEndIndex;\n","var trimmedEndIndex = require('./_trimmedEndIndex');\n\n/** Used to match leading whitespace. */\nvar reTrimStart = /^\\s+/;\n\n/**\n * The base implementation of `_.trim`.\n *\n * @private\n * @param {string} string The string to trim.\n * @returns {string} Returns the trimmed string.\n */\nfunction baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n}\n\nmodule.exports = baseTrim;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n","var Symbol = require('./_Symbol');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nmodule.exports = getRawTag;\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 nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nmodule.exports = objectToString;\n","var Symbol = require('./_Symbol'),\n getRawTag = require('./_getRawTag'),\n objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\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 != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\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) && baseGetTag(value) == symbolTag);\n}\n\nmodule.exports = isSymbol;\n","var baseTrim = require('./_baseTrim'),\n isObject = require('./isObject'),\n isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\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/**\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 = baseTrim(value);\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 = toNumber;\n","var isObject = require('./isObject'),\n now = require('./now'),\n toNumber = require('./toNumber');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\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 * 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 timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\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 clearTimeout(timerId);\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\nmodule.exports = debounce;\n","var debounce = require('./debounce'),\n isObject = require('./isObject');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a throttled function that only invokes `func` at most once per\n * every `wait` milliseconds. The throttled function comes with a `cancel`\n * method to cancel delayed `func` invocations and a `flush` method to\n * immediately invoke them. Provide `options` to indicate whether `func`\n * should be invoked on the leading and/or trailing edge of the `wait`\n * timeout. The `func` is invoked with the last arguments provided to the\n * throttled function. Subsequent calls to the throttled function return the\n * result of the last `func` 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 throttled 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 `_.throttle` and `_.debounce`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to throttle.\n * @param {number} [wait=0] The number of milliseconds to throttle invocations to.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=true]\n * Specify invoking on the leading edge of the timeout.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new throttled function.\n * @example\n *\n * // Avoid excessively updating the position while scrolling.\n * jQuery(window).on('scroll', _.throttle(updatePosition, 100));\n *\n * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.\n * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });\n * jQuery(element).on('click', throttled);\n *\n * // Cancel the trailing throttled invocation.\n * jQuery(window).on('popstate', throttled.cancel);\n */\nfunction throttle(func, wait, options) {\n var leading = true,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (isObject(options)) {\n leading = 'leading' in options ? !!options.leading : leading;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n return debounce(func, wait, {\n 'leading': leading,\n 'maxWait': wait,\n 'trailing': trailing\n });\n}\n\nmodule.exports = throttle;\n","import { Deferred } from \"./Deferred\";\nimport { log } from \"./log\";\nimport throttle from \"lodash/throttle\";\n\nexport const findVisibleElement = (selector: string) => {\n const el = findElement(selector);\n if (!el) return null;\n\n const rect = el.getBoundingClientRect();\n if (rect.width === 0 || rect.height === 0) return null;\n\n return el;\n};\n\nexport const findElement = (selector: string) => {\n try {\n if (!selector) return null;\n\n if (isXPathSelector(selector)) {\n return document.evaluate(selector, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)\n .singleNodeValue as Element | null;\n } else {\n return document.querySelector(selector);\n }\n } catch (e) {\n return null;\n }\n};\n\nfunction isXPathSelector(expression: string) {\n try {\n return (\n (expression.slice(0, 2) === \"//\" || expression.slice(0, 3) === \"(//\") &&\n document.evaluate(expression, document, null, XPathResult.ANY_TYPE, null) !== null\n );\n } catch (error) {\n return false;\n }\n}\n\nexport class ElementClicker {\n elementTracker: ElementTracker = new ElementTracker();\n isClicked = false;\n\n async clickElement(selector: string) {\n await this.elementTracker.trackElement(selector, (el) => {\n if (!this.isClicked) {\n this.isClicked = true;\n (el as HTMLElement | null)?.click();\n }\n\n this.elementTracker.stop();\n });\n }\n}\n\nexport class ElementTextWriter {\n startedTyping: boolean = false;\n\n async writeText(inputEl: HTMLInputElement, text: string, instantWrite = false) {\n let writeDelay = 0;\n if (this.startedTyping) {\n return;\n }\n inputEl.focus();\n this.startedTyping = true;\n if (instantWrite) {\n await this.writeLetter(inputEl, text, 0, 0);\n this.startedTyping = false;\n return;\n }\n await this.writeLetter(inputEl, text, 0, this.calculateDelay(text));\n this.startedTyping = false;\n }\n\n private writeLetter(el: HTMLInputElement, text: string, position: number, delay: number): Promise {\n return new Promise((resolve) => {\n if (position >= text.length) {\n resolve();\n return;\n }\n\n setTimeout(() => {\n const event = new Event(\"input\", { bubbles: true });\n const nativeInputValueSetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), \"value\")?.set;\n nativeInputValueSetter?.call(el, text.slice(0, position + 1));\n el.dispatchEvent(event);\n this.writeLetter(el, text, position + 1, delay).then(resolve);\n }, delay);\n });\n }\n\n private calculateDelay(text: string, minDelay = 20, baseDelay = 200, scalingFactor = 50) {\n let delay = baseDelay - Math.log(text.length + 1) * scalingFactor;\n delay = Math.max(minDelay, delay);\n return delay;\n }\n}\n\nexport class ElementTracker {\n elementSearcher: ElementSearcher = new ElementSearcher();\n disconnectObserver: Function | null = null;\n stopped: boolean = false;\n\n static readonly initialSearchTimeout = 1000;\n\n trackElement = async (\n selector: string,\n callback: (el: Element | null) => void,\n timeout = ElementTracker.initialSearchTimeout\n ) => {\n let lastElement: Element | undefined | null = undefined;\n\n const observer = new MutationObserver((mutations) => {\n const el = findVisibleElement(selector);\n if (el !== lastElement) {\n lastElement = el;\n callback(el);\n }\n });\n\n this.disconnectObserver = () => {\n observer.disconnect();\n log(\"stopped observing\", selector);\n };\n\n log(\"initial waitForElement\", selector);\n const el = await this.elementSearcher.waitForElement(selector, timeout);\n callback(el);\n lastElement = el;\n\n if (this.stopped) {\n log(\"stopped tracking element, will not observe\", selector);\n return;\n }\n\n observer.observe(document, {\n childList: true,\n subtree: true,\n attributes: true,\n characterData: true,\n });\n };\n\n trackElements = async (selectors: string[], callback: (els: Record) => void) => {\n let lastElements: Record = {};\n\n const observer = new MutationObserver((mutations) => {\n const els = selectors.reduce(\n (acc, selector) => {\n acc[selector] = findElement(selector);\n return acc;\n },\n {} as Record\n );\n\n const hasChanges = selectors.some((selector) => els[selector] !== lastElements[selector]);\n if (hasChanges) {\n lastElements = els;\n callback(els);\n }\n });\n\n this.disconnectObserver = () => {\n observer.disconnect();\n log(\"stopped observing\", selectors);\n };\n\n const elementsArray = await Promise.all(\n selectors.map((selector) => this.elementSearcher.waitForElement(selector, ElementTracker.initialSearchTimeout))\n );\n\n const elementsRecord = selectors.reduce(\n (acc, selector, index) => {\n acc[selector] = elementsArray[index];\n return acc;\n },\n {} as Record\n );\n\n callback(elementsRecord);\n lastElements = elementsRecord;\n\n if (this.stopped) {\n log(\"stopped tracking elements, will not observe\", selectors);\n return;\n }\n\n observer.observe(document, {\n childList: true,\n subtree: true,\n attributes: true,\n characterData: true,\n });\n };\n\n stop = () => {\n this.stopped = true;\n this.elementSearcher.cancelAll();\n this.disconnectObserver?.();\n };\n}\n\nexport class ElementSearcher {\n cancelled: boolean;\n\n constructor() {\n this.cancelled = false;\n }\n\n cancelAll() {\n this.cancelled = true;\n }\n\n waitForElement = async (selector: string, timeout?: number): Promise => {\n const findThisElement = () => findVisibleElement(selector);\n\n // check if element is already available\n const el = findThisElement();\n if (el) {\n log(\"element already available from first try\", selector);\n return Promise.resolve(el);\n }\n\n const defferedFind = new Deferred();\n\n const check = throttle(() => {\n if (this.cancelled) {\n log(\"cancelled waitForElement\", selector);\n defferedFind.resolve(null);\n return;\n }\n\n const el = findThisElement();\n if (el) {\n log(\"found element\", selector);\n defferedFind.resolve(el);\n }\n }, 100);\n\n const observer = new MutationObserver(() => {\n check();\n });\n\n observer.observe(document, {\n childList: true,\n subtree: true,\n attributes: true,\n characterData: true,\n });\n\n const intervalId = setInterval(() => {\n check();\n }, 1000);\n\n let timeoutId: any;\n if (timeout) {\n timeoutId = setTimeout(() => {\n log(\"wait for selector timeout triggered\", timeout);\n defferedFind.resolve(null);\n }, timeout);\n }\n\n // wait for deffered to resolve\n const result = await defferedFind.promise;\n log(\"wait result\", result);\n\n // cleanup\n observer.disconnect();\n clearInterval(intervalId);\n clearTimeout(timeoutId);\n\n return result;\n };\n}\n","import type * as schemas from \"@common/schemas/v2\";\nimport * as models from \"@common/models/v2\";\nimport { BaseStep } from \"./base\";\nimport { openNewTab, openNewWindow, openSameTab } from \"@/lib/window\";\nimport { StepActions } from \"./step\";\nimport { ElementClicker } from \"@/lib/element\";\nimport { makeObservable, observable, override } from \"mobx\";\nimport { FlowFlexibility } from \"@common/schemas\";\n\nexport type ModalStep = MultipleChoiceModalStep;\nexport type ModalChoice =\n | FinishTourModalChoice\n | ProceedNextModalChoice\n | LinkModalChoice\n | SwitchTourModalChoice\n | SuspendTourModalChoice\n | TriggerClickModalChoice;\n\nexport class MultipleChoiceModalStep extends BaseStep {\n attributes: models.MultipleChoiceModalStepAttributes;\n actions: StepActions;\n choices!: ModalChoice[];\n variant?: string;\n isAnswered = false;\n allowProceed = false;\n\n constructor(step: schemas.Step, actions: StepActions, flowFlexibility: FlowFlexibility) {\n super(step, actions, flowFlexibility);\n this.attributes = new models.MultipleChoiceModalStepAttributes(\n step.attributes as schemas.MultipleChoiceModalStepAttributes\n );\n this.actions = actions;\n this.variant = this.attributes.variant;\n\n this.initializeChoices(actions);\n\n makeObservable(this, {\n isAnswered: observable,\n isBlocking: override,\n allowProceed: observable,\n });\n }\n\n initializeChoices(actions: StepActions) {\n if (this.variant === \"theydo\") {\n this.choices = this.theydoChoices(actions);\n return;\n }\n\n this.choices = ModalChoiceFactory.createList(this.attributes.choices, actions);\n }\n\n theydoChoices(actions: StepActions) {\n return [\n new ProceedNextModalChoice(\n {\n id: \"notNow\",\n type: \"proceedNext\",\n text: \"Not now\",\n buttonVariant: \"primary\",\n },\n actions\n ),\n new TriggerClickModalChoice(\n {\n id: \"unlock\",\n type: \"triggerClick\",\n text: \"Show me\",\n selector: '//*[@id=\"app\"]/div/div[1]/nav/div/div[3]/div/div/div/span/button',\n buttonVariant: \"primary\",\n },\n actions\n ),\n ];\n }\n\n async run() {\n this.isAnswered = false;\n this.allowProceed = false;\n }\n\n async answer(choiceId: string) {\n const choice = this.choices.find((c) => c.id === choiceId);\n if (!choice) {\n return;\n }\n super.emitter.emit(\"modalAnswered\", { choice });\n this.isAnswered = true;\n\n const { allowProceed } = await choice.execute();\n this.allowProceed = allowProceed;\n }\n\n get isBlocking() {\n return !this.allowProceed;\n }\n\n get isBlockingStepType() {\n return true;\n }\n\n get modal() {\n if (this.isAnswered) {\n return null;\n }\n\n return {\n title: this.attributes.title,\n modalContent: this.attributes.modalContent,\n choices: this.choices,\n description: this.attributes.description,\n variant: this.attributes.variant,\n };\n }\n}\n\nexport class FinishTourModalChoice {\n id: string;\n type = \"finishTour\";\n text: string;\n buttonVariant: schemas.ChoiceButtonVariant;\n actions: StepActions;\n\n constructor(choice: schemas.ModalFinishTourChoice, actions: StepActions) {\n const finishTourChoice = new models.FinishTourModalChoice(choice);\n this.id = finishTourChoice.id;\n this.text = finishTourChoice.text;\n this.buttonVariant = finishTourChoice.buttonVariant;\n this.actions = actions;\n }\n\n execute() {\n this.actions.finishTour();\n return { allowProceed: false };\n }\n}\n\nexport class ProceedNextModalChoice {\n id: string;\n type = \"proceedNext\";\n text: string;\n buttonVariant: schemas.ChoiceButtonVariant;\n actions: StepActions;\n\n constructor(choice: schemas.ProceedNextChoice, actions: StepActions) {\n const proceedNextChoice = new models.ProceedNextModalChoice(choice);\n this.id = proceedNextChoice.id;\n this.text = proceedNextChoice.text;\n this.buttonVariant = proceedNextChoice.buttonVariant;\n this.actions = actions;\n }\n\n execute() {\n return { allowProceed: true };\n }\n}\n\nexport class ContactSupportModalChoice {\n id: string;\n type = \"contactSupport\";\n text: string;\n url: string;\n actions: StepActions;\n buttonVariant: schemas.ChoiceButtonVariant = \"primary\";\n\n constructor(choice: schemas.ContactSupportChoice, actions: StepActions) {\n const contactSupportChoice = new models.ContactSupportModalChoice(choice);\n this.id = contactSupportChoice.id;\n this.url = contactSupportChoice.url;\n this.text = contactSupportChoice.text;\n this.actions = actions;\n this.buttonVariant = contactSupportChoice.buttonVariant;\n }\n\n execute() {\n openNewTab(this.url);\n return { allowProceed: true };\n }\n}\n\nexport class LinkModalChoice {\n id: string;\n text: string;\n windowType: schemas.LinkChoiceWindowType;\n url: string;\n actions: StepActions;\n buttonVariant: schemas.ChoiceButtonVariant;\n\n constructor(choice: schemas.LinkChoice, actions: StepActions) {\n const linkChoice = new models.LinkChoice(choice);\n\n this.id = linkChoice.id;\n this.text = linkChoice.text;\n this.windowType = linkChoice.windowType;\n this.url = linkChoice.url;\n this.actions = actions;\n this.buttonVariant = linkChoice.buttonVariant;\n }\n\n execute() {\n switch (this.windowType) {\n case \"newTab\":\n openNewTab(this.url);\n break;\n case \"sameTab\":\n openSameTab(this.url);\n break;\n case \"newWindow\":\n openNewWindow(this.url);\n break;\n default:\n openNewTab(this.url);\n break;\n }\n return { allowProceed: true };\n }\n}\n\nexport class SwitchTourModalChoice {\n id: string;\n type = \"switchTour\";\n text: string;\n guideId: string;\n actions: StepActions;\n buttonVariant: schemas.ChoiceButtonVariant = \"primary\";\n constructor(choice: schemas.SwitchTourChoice, actions: StepActions) {\n const switchTourChoice = new models.SwitchTourChoice(choice);\n this.id = switchTourChoice.id;\n this.text = switchTourChoice.text;\n this.guideId = switchTourChoice.guideId;\n this.actions = actions;\n this.buttonVariant = switchTourChoice.buttonVariant;\n }\n\n execute() {\n this.actions.switchTour(this.guideId);\n return { allowProceed: false };\n }\n}\n\nexport class TriggerClickModalChoice {\n id: string;\n type = \"triggerClick\";\n text: string;\n selector: string;\n actions: StepActions;\n buttonVariant: schemas.ChoiceButtonVariant = \"primary\";\n\n constructor(choice: schemas.TriggerClickChoice, actions: StepActions) {\n const triggerClickChoice = new models.TriggerClickModalChoice(choice);\n this.id = triggerClickChoice.id;\n this.text = triggerClickChoice.text;\n this.selector = triggerClickChoice.selector;\n this.actions = actions;\n this.buttonVariant = triggerClickChoice.buttonVariant;\n }\n\n async execute() {\n const elementClicker = new ElementClicker();\n await elementClicker.clickElement(this.selector);\n return { allowProceed: true };\n }\n}\n\nexport class SuspendTourModalChoice {\n id: string;\n type = \"suspendTour\";\n text: string;\n actions: StepActions;\n buttonVariant: schemas.ChoiceButtonVariant = \"primary\";\n\n constructor(choice: schemas.SuspendTourChoice, actions: StepActions) {\n const suspendTourChoice = new models.SuspendTourModalChoice(choice);\n this.id = suspendTourChoice.id;\n this.text = suspendTourChoice.text;\n this.actions = actions;\n this.buttonVariant = suspendTourChoice.buttonVariant;\n }\n\n execute() {\n this.actions.suspendTour();\n return { allowProceed: false };\n }\n}\n\nexport class ModalFactory {\n static create(step: schemas.ModalStep, actions: StepActions, flowFlexibility: FlowFlexibility): ModalStep {\n switch (step.attributes.questionType) {\n case \"multipleChoice\":\n return new MultipleChoiceModalStep(step, actions, flowFlexibility);\n default:\n throw new Error(`Unknown modal type: ${step.attributes.type}`);\n }\n }\n}\n\nexport class ModalChoiceFactory {\n static create(choice: schemas.ModalChoice, actions: StepActions): ModalChoice {\n switch (choice.type) {\n case \"finishTour\":\n return new FinishTourModalChoice(choice as schemas.ModalFinishTourChoice, actions);\n case \"proceedNext\":\n return new ProceedNextModalChoice(choice as schemas.ModalProceedNextChoice, actions);\n case \"link\":\n return new LinkModalChoice(choice as schemas.ModalLinkChoice, actions);\n case \"contactSupport\":\n return new ContactSupportModalChoice(choice as schemas.ModalContactSupportChoice, actions);\n case \"switchTour\":\n return new SwitchTourModalChoice(choice as schemas.ModalSwitchTourChoice, actions);\n case \"suspendTour\":\n return new SuspendTourModalChoice(choice as schemas.ModalSuspendTourChoice, actions);\n case \"triggerClick\":\n return new TriggerClickModalChoice(choice as schemas.ModalTriggerClickChoice, actions);\n default:\n throw new Error(`Unknown modal choice type: ${(choice as schemas.ModalChoice).type}`);\n }\n }\n static createList(choices: schemas.ModalChoice[], actions: StepActions): ModalChoice[] {\n return choices?.length\n ? choices.map((choice) => this.create(choice, actions))\n : [this.createDefaultChoice(actions)];\n }\n\n private static createDefaultChoice(actions: StepActions): ModalChoice {\n return new ProceedNextModalChoice(\n {\n id: \"defaultChoice\",\n type: \"proceedNext\",\n text: \"Continue\",\n buttonVariant: \"primary\",\n },\n actions\n );\n }\n}\n","import type * as schemas from \"@common/schemas/v2\";\nimport * as models from \"@common/models/v2\";\nimport { BaseStep } from \"./base\";\nimport { openNewTab, openNewWindow, openSameTab } from \"@/lib/window\";\nimport { ElementClicker } from \"@/lib/element\";\nimport { StepActions } from \"./step\";\nimport { makeObservable, observable, override } from \"mobx\";\nimport { FlowFlexibility } from \"@common/schemas\";\n\nexport type QuestionStep = MultipleChoiceQuestionStep;\nexport type QuestionChoice =\n | LinkChoice\n | ProceedNextChoice\n | SuspendTourChoice\n | FinishTourChoice\n | TriggerClickChoice\n | SwitchTourChoice\n | ContactSupportChoice\n | LoadCheckpointChoice;\n\nexport class MultipleChoiceQuestionStep extends BaseStep {\n attributes: models.MultipleChoiceQuestionStepAttributes;\n actions: StepActions;\n\n choices: QuestionChoice[];\n isAnswered = false;\n isDisposed = false;\n allowProceed = false;\n\n constructor(step: schemas.Step, actions: StepActions, flowFlexibility: FlowFlexibility) {\n super(step, actions, flowFlexibility);\n this.attributes = new models.MultipleChoiceQuestionStepAttributes(\n step.attributes as schemas.MultipleChoiceQuestionStepAttributes\n );\n this.actions = actions;\n this.choices = QuestionChoiceFactory.createList(this.attributes.choices, actions);\n makeObservable(this, {\n isAnswered: observable,\n isDisposed: observable,\n allowProceed: observable,\n isBlocking: override,\n });\n }\n\n async run() {\n super.run();\n this.isAnswered = false;\n this.isDisposed = false;\n this.allowProceed = false;\n }\n\n async finish() {\n super.finish();\n }\n\n async answer(choiceId: string) {\n const choice = this.choices.find((c) => c.id === choiceId);\n if (!choice) {\n return;\n }\n super.emitter.emit(\"questionAnswered\", { choice });\n this.isAnswered = true;\n\n const { allowProceed } = await choice.execute();\n this.allowProceed = allowProceed;\n }\n\n dispose(): void {\n super.dispose();\n this.isDisposed = true;\n }\n\n get prompt() {\n if (this.isAnswered || this.isDisposed) {\n return null;\n }\n\n return {\n type: \"multipleChoice\",\n title: this.attributes.title,\n text: this.attributes.text,\n choices: this.choices,\n };\n }\n\n get additionalContent() {\n return this.attributes?.additionalContent;\n }\n\n get isBlocking() {\n return !this.allowProceed;\n }\n\n get isBlockingStepType() {\n return true;\n }\n\n get skipStepOnEarlyUnblock() {\n return true;\n }\n}\n\nexport class LinkChoice {\n id: string;\n text: string;\n windowType: schemas.LinkChoiceWindowType;\n url: string;\n actions: StepActions;\n buttonVariant: schemas.ChoiceButtonVariant = \"primary\";\n\n constructor(choice: schemas.LinkChoice, actions: StepActions) {\n const linkChoice = new models.LinkChoice(choice);\n\n this.id = linkChoice.id;\n this.text = linkChoice.text;\n this.windowType = linkChoice.windowType;\n this.url = linkChoice.url;\n this.actions = actions;\n this.buttonVariant = linkChoice.buttonVariant;\n }\n\n execute() {\n switch (this.windowType) {\n case \"newTab\":\n openNewTab(this.url);\n break;\n case \"sameTab\":\n openSameTab(this.url);\n break;\n case \"newWindow\":\n openNewWindow(this.url);\n break;\n default:\n openNewTab(this.url);\n break;\n }\n\n return { allowProceed: true };\n }\n}\n\nexport class SwitchTourChoice {\n id: string;\n type = \"switchTour\";\n text: string;\n guideId: string;\n actions: StepActions;\n buttonVariant: schemas.ChoiceButtonVariant = \"primary\";\n\n constructor(choice: schemas.SwitchTourChoice, actions: StepActions) {\n const switchTourChoice = new models.SwitchTourChoice(choice);\n this.id = switchTourChoice.id;\n this.text = switchTourChoice.text;\n this.guideId = switchTourChoice.guideId;\n this.actions = actions;\n this.buttonVariant = switchTourChoice.buttonVariant;\n }\n\n execute() {\n this.actions.switchTour(this.guideId);\n return { allowProceed: false };\n }\n}\n\nexport class ProceedNextChoice {\n id: string;\n type = \"proceedNext\";\n text: string;\n actions: StepActions;\n buttonVariant: schemas.ChoiceButtonVariant = \"primary\";\n\n constructor(choice: schemas.ProceedNextChoice, actions: StepActions) {\n const proceedNextChoice = new models.ProceedNextChoice(choice);\n this.id = proceedNextChoice.id;\n this.text = proceedNextChoice.text;\n this.actions = actions;\n this.buttonVariant = proceedNextChoice.buttonVariant;\n }\n\n execute() {\n return { allowProceed: true };\n }\n}\n\nexport class SuspendTourChoice {\n id: string;\n type = \"suspendTour\";\n text: string;\n actions: StepActions;\n buttonVariant: schemas.ChoiceButtonVariant = \"primary\";\n\n constructor(choice: schemas.SuspendTourChoice, actions: StepActions) {\n const suspendTourChoice = new models.SuspendTourChoice(choice);\n this.id = suspendTourChoice.id;\n this.text = suspendTourChoice.text;\n this.actions = actions;\n this.buttonVariant = suspendTourChoice.buttonVariant;\n }\n\n execute() {\n this.actions.suspendTour();\n return { allowProceed: false };\n }\n}\n\nexport class FinishTourChoice {\n id: string;\n type = \"finishTour\";\n text: string;\n actions: StepActions;\n buttonVariant: schemas.ChoiceButtonVariant = \"primary\";\n constructor(choice: schemas.FinishTourChoice, actions: StepActions) {\n const finishTourChoice = new models.FinishTourChoice(choice);\n this.id = finishTourChoice.id;\n this.text = finishTourChoice.text;\n this.actions = actions;\n this.buttonVariant = finishTourChoice.buttonVariant;\n }\n\n execute() {\n this.actions.finishTour();\n return { allowProceed: false };\n }\n}\n\nexport class TriggerClickChoice {\n id: string;\n type = \"triggerClick\";\n text: string;\n selector: string;\n actions: StepActions;\n buttonVariant: schemas.ChoiceButtonVariant = \"primary\";\n\n constructor(choice: schemas.TriggerClickChoice, actions: StepActions) {\n const triggerClickChoice = new models.TriggerClickChoice(choice);\n this.id = triggerClickChoice.id;\n this.text = triggerClickChoice.text;\n this.selector = triggerClickChoice.selector;\n this.actions = actions;\n this.buttonVariant = triggerClickChoice.buttonVariant;\n }\n\n async execute() {\n const elementClicker = new ElementClicker();\n await elementClicker.clickElement(this.selector);\n return { allowProceed: true };\n }\n}\n\nexport class ContactSupportChoice {\n id: string;\n type = \"contactSupport\";\n text: string;\n url: string;\n actions: StepActions;\n buttonVariant: schemas.ChoiceButtonVariant = \"primary\";\n\n constructor(choice: schemas.ContactSupportChoice, actions: StepActions) {\n const contactSupportChoice = new models.ContactSupportChoice(choice);\n this.id = contactSupportChoice.id;\n this.text = contactSupportChoice.text;\n this.url = contactSupportChoice.url;\n this.actions = actions;\n this.buttonVariant = contactSupportChoice.buttonVariant;\n }\n\n execute() {\n openNewTab(this.url);\n return { allowProceed: true };\n }\n}\n\nexport class LoadCheckpointChoice {\n id: string;\n type = \"loadCheckpoint\";\n text: string;\n actions: StepActions;\n buttonVariant: schemas.ChoiceButtonVariant = \"primary\";\n\n constructor(choice: schemas.LoadCheckpointChoice, actions: StepActions) {\n const loadCheckpointChoice = new models.LoadCheckpointChoice(choice);\n this.id = loadCheckpointChoice.id;\n this.text = loadCheckpointChoice.text;\n this.actions = actions;\n this.buttonVariant = loadCheckpointChoice.buttonVariant;\n }\n\n execute() {\n this.actions.loadLastCheckpoint();\n return { allowProceed: false };\n }\n}\n\nexport class QuestionFactory {\n static create(step: schemas.QuestionStep, actions: StepActions, flowFlexibility: FlowFlexibility): QuestionStep {\n switch (step.attributes.questionType) {\n case \"multipleChoice\":\n return new MultipleChoiceQuestionStep(step, actions, flowFlexibility);\n default:\n throw new Error(`Unknown question type: ${(step as schemas.QuestionStep).attributes.questionType}`);\n }\n }\n}\n\nexport class QuestionChoiceFactory {\n static create(choice: schemas.QuestionChoice, actions: StepActions): QuestionChoice {\n switch (choice.type) {\n case \"link\":\n return new LinkChoice(choice as schemas.LinkChoice, actions);\n case \"proceedNext\":\n return new ProceedNextChoice(choice as schemas.ProceedNextChoice, actions);\n case \"suspendTour\":\n return new SuspendTourChoice(choice as schemas.SuspendTourChoice, actions);\n case \"finishTour\":\n return new FinishTourChoice(choice as schemas.FinishTourChoice, actions);\n case \"switchTour\":\n return new SwitchTourChoice(choice as schemas.SwitchTourChoice, actions);\n case \"triggerClick\":\n return new TriggerClickChoice(choice as schemas.TriggerClickChoice, actions);\n case \"contactSupport\":\n return new ContactSupportChoice(choice as schemas.ContactSupportChoice, actions);\n case \"loadCheckpoint\":\n return new LoadCheckpointChoice(choice as schemas.LoadCheckpointChoice, actions);\n default:\n throw new Error(`Unknown question choice type: ${(choice as any).type}`);\n }\n }\n\n static createList(choices: schemas.QuestionChoice[], actions: StepActions): QuestionChoice[] {\n if (choices.length === 0) {\n const defaultChoice = new ProceedNextChoice(\n { id: \"defaultChoice\", type: \"proceedNext\", text: \"Continue\", buttonVariant: \"primary\" },\n actions\n );\n return [defaultChoice];\n }\n\n return choices.map((choice) => this.create(choice, actions));\n }\n}\n\nexport function isTourSwitchChoice(choice: any): choice is SwitchTourChoice {\n return choice.type === \"switchTour\" && \"guideId\" in choice;\n}\n","import { getWindow } from \"./window\";\n\nexport interface StorageHandler {\n isKeyExists(key: string): boolean;\n get(key: string, defaultValue: any): any;\n remove(key: string): void;\n set(key: string, value: any): void;\n}\n\nexport const createLocalStorageHandler = (): StorageHandler => {\n return {\n isKeyExists: (key: string) => {\n return isKeyInLocalStorage(key);\n },\n get: (key: string, defaultValue: any) => {\n return getFromLocalStorage(key, defaultValue);\n },\n remove: (key: string) => {\n removeFromLocalStorage(key);\n },\n set: (key: string, value: any) => {\n setToLocalStorage(key, value);\n },\n };\n};\n\nexport const createSessionStorageHandler = (): StorageHandler => {\n return {\n isKeyExists: (key: string) => {\n return isKeyInSessionStorage(key);\n },\n get: (key: string, defaultValue: any) => {\n return getFromSessionStorage(key, defaultValue);\n },\n remove: (key: string) => {\n removeFromSessionStorage(key);\n },\n set: (key: string, value: any) => {\n setToSessionStorage(key, value);\n },\n };\n};\n\nexport const createInMemoryStorageHandler = (): StorageHandler => {\n const storage: { [key: string]: any } = {};\n\n return {\n isKeyExists: (key: string) => key in storage,\n get: (key: string, defaultValue: any) => (key in storage ? storage[key] : defaultValue),\n remove: (key: string) => {\n delete storage[key];\n },\n set: (key: string, value: any) => {\n storage[key] = value;\n },\n };\n};\n\nexport const getFromLocalStorage = (key: string, defaultValue: any) => {\n if (typeof window === \"undefined\") return null;\n const value = localStorage.getItem(key);\n if (!value) {\n return defaultValue;\n }\n try {\n return JSON.parse(value);\n } catch (e) {\n return defaultValue;\n }\n};\n\nexport const setToLocalStorage = (key: string, value: any) => {\n if (typeof window === \"undefined\") return;\n localStorage.setItem(key, JSON.stringify(value));\n};\n\nexport const isKeyInLocalStorage = (key: string) => {\n if (typeof window === \"undefined\") return false;\n return localStorage.getItem(key) !== null;\n};\n\nexport const removeFromLocalStorage = (key: string) => {\n if (typeof window === \"undefined\") return;\n localStorage.removeItem(key);\n};\n\nexport const getFromSessionStorage = (key: string, defaultValue: any) => {\n if (typeof window === \"undefined\") return null;\n const value = sessionStorage.getItem(key);\n if (!value) {\n return defaultValue;\n }\n try {\n return JSON.parse(value);\n } catch (e) {\n return defaultValue;\n }\n};\n\nexport const isKeyInSessionStorage = (key: string) => {\n if (typeof window === \"undefined\") return false;\n return sessionStorage.getItem(key) !== null;\n};\n\nexport const setToSessionStorage = (key: string, value: any) => {\n if (typeof window === \"undefined\") return;\n sessionStorage.setItem(key, JSON.stringify(value));\n};\n\nexport const removeFromSessionStorage = (key: string) => {\n if (typeof window === \"undefined\") return;\n sessionStorage.removeItem(key);\n};\n\nexport const sendStorageEvent = (key: string, oldValue?: string, newValue?: string) => {\n const event = new StorageEvent(\"storage\", {\n key,\n newValue,\n oldValue,\n });\n getWindow().dispatchEvent(event);\n};\n","import { createInMemoryStorageHandler, StorageHandler } from \"@/lib/storage\";\n\nexport interface AvatarState {\n isCaptionsVisible: boolean;\n isMuted: boolean;\n}\n\nexport type AvatarStateStorage = ReturnType;\n\nconst storageKey = (isPreview: boolean) => `pyne-avatar-state${isPreview ? `-preview` : \"\"}`;\n\nexport const buildAvatarStateStorage = (isPreview: boolean, storage: StorageHandler) => {\n const self = () => buildAvatarStateStorage(isPreview, storage);\n return {\n key: () => {\n return storageKey(isPreview);\n },\n get: (): AvatarState => {\n return storage.get(storageKey(isPreview), {\n isCaptionsVisible: true,\n isMuted: false,\n });\n },\n clear: () => {\n storage.remove(storageKey(isPreview));\n },\n set: (state: Partial) => {\n storage.set(storageKey(isPreview), { ...self().get(), ...state });\n },\n };\n};\n\nexport const buildInMemoryAvatarStateStorage = () => buildAvatarStateStorage(false, createInMemoryStorageHandler());\n","import { Checkpoint } from \"./tourPlayback\";\n\nexport const findLastCheckpoint = (checkpoints: Checkpoint[]) => {\n if (!checkpoints || checkpoints.length === 0) {\n return null;\n }\n\n const lastCheckpointTrace = checkpoints[checkpoints.length - 1];\n\n const stepCheckpointTraces = checkpoints.filter((checkpoint) => checkpoint.stepId === lastCheckpointTrace.stepId);\n if (stepCheckpointTraces.length === 0) {\n return null;\n }\n\n return stepCheckpointTraces[0];\n};\n","import { StorageHandler, createInMemoryStorageHandler } from \"@/lib/storage\";\nimport { getWindow } from \"@/lib/window\";\nimport { Checkpoint } from \"../tourPlayback\";\nimport { uuid } from \"@/lib/utils\";\nimport { findLastCheckpoint } from \"../checkpoint\";\n\nexport interface TourState {\n activeTourGuideId?: string;\n activeStepId?: string;\n lastStepTransitionTimestamp?: number;\n checkpoints?: Checkpoint[];\n tabId?: string;\n tourPlaybackVersion?: string;\n lastCompletedStepId?: string;\n hasWatchedIntro?: boolean;\n lastPageUrl?: string;\n isSuspended?: boolean;\n suspendReason?: string;\n expirationTimeoutMinutes?: number;\n startedAt?: number;\n sessionId?: string;\n}\n\nexport type TourStateStorage = ReturnType;\n\nconst storageKey = (suffix: boolean) => `pyne-tour-state${suffix ? `-preview` : \"\"}`;\nexport const buildTourStateStorage = (suffix: boolean, storage: StorageHandler) => {\n const self = () => buildTourStateStorage(suffix, storage);\n return {\n key: () => {\n return storageKey(suffix);\n },\n get: (): TourState => {\n return storage.get(storageKey(suffix), { checkpoints: [] });\n },\n clear: () => {\n storage.remove(storageKey(suffix));\n },\n set: (state: Partial) => {\n storage.set(storageKey(suffix), { ...self().get(), ...state });\n },\n setCheckpoints: (checkpoints: Checkpoint[]) => {\n self().set({ checkpoints });\n },\n listCheckpoints: (): Checkpoint[] => {\n return self().get().checkpoints || [];\n },\n getLastCheckpoint: (): Checkpoint | null => {\n const checkpoints = self().listCheckpoints();\n if (checkpoints.length === 0) {\n return null;\n }\n\n return findLastCheckpoint(checkpoints);\n },\n setLastCheckpointUrl: (stepId: string, url: string) => {\n const checkpoints = self().listCheckpoints();\n const checkpointIndex = checkpoints.findIndex((checkpoint) => checkpoint.stepId === stepId);\n if (checkpointIndex === -1) {\n return;\n }\n\n checkpoints[checkpointIndex].url = url;\n self().set({ checkpoints });\n },\n removeCheckpointByStepId: (stepId: string) => {\n const checkpoints = self().listCheckpoints();\n const checkpointIndex = checkpoints.findIndex((checkpoint) => checkpoint.stepId === stepId);\n if (checkpointIndex === -1) {\n return;\n }\n\n checkpoints.splice(checkpointIndex, 1);\n self().set({ checkpoints });\n },\n setLastCompletedStepId: (stepId: string) => {\n self().set({ lastCompletedStepId: stepId });\n },\n getLastCompletedStepId: () => {\n return self().get().lastCompletedStepId;\n },\n onTabChange: (callback: (tabId: string) => void) => {\n getWindow().addEventListener(\"storage\", (event) => {\n if (event.key === storageKey(suffix)) {\n const oldState = JSON.parse(event.oldValue || \"{}\") as TourState;\n const newState = JSON.parse(event.newValue || \"{}\") as TourState;\n\n if (oldState.tabId !== newState.tabId) {\n callback(newState.tabId!);\n }\n }\n });\n },\n getTabId: () => {\n return self().get().tabId;\n },\n setTabId: (tabId: string) => {\n self().set({ tabId });\n },\n setHasWatchedIntro: (value: boolean) => {\n self().set({ hasWatchedIntro: value });\n },\n getHasWatchedIntro: () => {\n return self().get().hasWatchedIntro;\n },\n getIsSuspended: () => {\n return self().get().isSuspended;\n },\n setIsSuspended: (isSuspended: boolean) => {\n self().set({ isSuspended });\n },\n initStartedAt: () => {\n const state = self().get();\n if (state.startedAt) {\n return state.startedAt;\n }\n\n const time = Date.now();\n self().set({ startedAt: time });\n return time;\n },\n initSessionId: () => {\n const state = self().get();\n if (state.sessionId) {\n return state.sessionId;\n }\n\n const sessionId = uuid();\n self().set({ sessionId });\n return sessionId;\n },\n };\n};\n\nexport const buildInMemoryTourStateStorage = () => buildTourStateStorage(false, createInMemoryStorageHandler());\n","import parseDuration from \"parse-duration\";\nexport const comparisonTypes = [\n \"eq\",\n \"neq\",\n \"gte\",\n \"lte\",\n \"gt\",\n \"lt\",\n \"in\",\n \"contains\",\n \"not_contains\",\n \"starts\",\n \"ends_with\",\n \"is_null\",\n \"is_not_null\",\n \"is_older_than_duration\",\n \"is_newer_than_duration\",\n];\nexport const comparisonTypeText = {\n eq: \"equals\",\n neq: \"does not equal\",\n gte: \"is greater than or equal to\",\n lte: \"is less than or equal to\",\n gt: \"is greater than\",\n lt: \"is less than\",\n in: \"is one of\",\n contains: \"contains\",\n not_contains: \"does not contain\",\n starts: \"starts with\",\n ends_with: \"ends with\",\n is_null: \"is unknown\",\n is_not_null: \"is any\",\n is_older_than_duration: \"is older than duration\",\n is_newer_than_duration: \"is newer than duration\",\n};\nconst baseOperations = {\n eq: (value, predicateValue) => value === predicateValue,\n neq: (value, predicateValue) => value !== predicateValue,\n in: (value, predicateValue) => predicateValue.split(\",\").includes(value),\n gte: (value, predicateValue) => value >= predicateValue,\n lte: (value, predicateValue) => value <= predicateValue,\n gt: (value, predicateValue) => value > predicateValue,\n lt: (value, predicateValue) => value < predicateValue,\n is_null: (value) => value === null,\n is_not_null: (value) => value !== null,\n // these intended to be implemented by specific types\n contains: (value, predicateValue) => false,\n not_contains: (value, predicateValue) => false,\n starts: (value, predicateValue) => false,\n ends_with: (value, predicateValue) => false,\n is_older_than_duration: (value, predicateValue) => false,\n is_newer_than_duration: (value, predicateValue) => false,\n};\nconst stringOperations = {\n contains: (value, predicateValue) => value !== null && value.includes(predicateValue),\n not_contains: (value, predicateValue) => value !== null && !value.includes(predicateValue),\n starts: (value, predicateValue) => value !== null && value.startsWith(predicateValue),\n ends_with: (value, predicateValue) => value !== null && value.endsWith(predicateValue),\n};\nconst dateOperations = {\n eq: (value, predicateValue) => new Date(value) === new Date(predicateValue),\n neq: (value, predicateValue) => new Date(value) !== new Date(predicateValue),\n gte: (value, predicateValue) => new Date(value) >= new Date(predicateValue),\n lte: (value, predicateValue) => new Date(value) <= new Date(predicateValue),\n gt: (value, predicateValue) => new Date(value) > new Date(predicateValue),\n lt: (value, predicateValue) => new Date(value) < new Date(predicateValue),\n is_older_than_duration: (value, predicateValue) => {\n const duration = parseDuration(predicateValue);\n if (!duration || isNaN(duration))\n return false;\n return new Date(value) < new Date(Date.now() - duration);\n },\n is_newer_than_duration: (value, predicateValue) => {\n const duration = parseDuration(predicateValue);\n if (!duration || isNaN(duration))\n return false;\n return new Date(value) > new Date(Date.now() - duration);\n },\n};\nexport function matchesCondition(condition, user) {\n const evaluatedPredicates = condition.predicates.map((predicate) => {\n const value = inferType(user[predicate.attribute]);\n const operationMap = (value) => {\n if (typeof value === \"string\") {\n return { ...baseOperations, ...stringOperations };\n }\n if (value instanceof Date) {\n return { ...baseOperations, ...dateOperations };\n }\n return baseOperations;\n };\n const op = operationMap(value)[predicate.comparison];\n const result = op(value, predicate.value);\n return {\n predicate,\n result,\n value: value === undefined ? \"[undefined]\" : value,\n };\n });\n const mainResult = {\n evaluatedPredicates,\n type: condition.type,\n result: evaluatedPredicates[condition.type === \"all\" ? \"every\" : \"some\"]((predicate) => predicate.result),\n };\n return mainResult;\n}\nexport function inferType(value) {\n if (typeof value !== \"string\")\n return value;\n if (value === \"true\")\n return true;\n if (value === \"false\")\n return false;\n if (!isNaN(Number(value)))\n return Number(value);\n if (!isNaN(Date.parse(value)))\n return new Date(value);\n return value;\n}\nexport function getGuideTargetingEvaluation(guide, mergedUserData) {\n const matchResult = guide.targeting?.who ? matchesCondition(guide.targeting.who, mergedUserData) : undefined;\n const targetingEvaluation = {\n isPublished: !!guide.published_at,\n isGenerated: guide.version === 2 ? !!guide.tour_playback : true,\n whoMatch: matchResult,\n isWhoTargeted: matchResult?.result ?? true,\n };\n return targetingEvaluation;\n}\nexport function parseRoutePattern(path, currentUrl) {\n const currentPath = new URL(currentUrl).pathname;\n const currentRoutes = currentPath.split(\"/\");\n return path\n .split(\"/\")\n .map((r, index) => (r === \"*\" ? currentRoutes[index] : r))\n .join(\"/\");\n}\nexport function checkUrlCondition(urlCondition, currentUrl) {\n const parsedUrl = parseRoutePattern(urlCondition.right_operand, currentUrl);\n if (urlCondition.operator === \"equals\") {\n return parsedUrl === currentUrl;\n }\n else if (urlCondition.operator === \"contains\") {\n return currentUrl.includes(parsedUrl);\n }\n else if (urlCondition.operator === \"not_contains\") {\n return !currentUrl.includes(parsedUrl);\n }\n else if (urlCondition.operator === \"starts_with\") {\n return currentUrl.startsWith(parsedUrl);\n }\n else if (urlCondition.operator === \"ends_with\") {\n return currentUrl.endsWith(parsedUrl);\n }\n return false;\n}\nexport function calculateLocalTimeConditionDelta(localTimeCondition, localTime) {\n const targetedLocalTime = new Date(Date.parse(localTimeCondition.right_operand));\n const localTotalSeconds = localTime.getHours() * 3600 + localTime.getMinutes() * 60;\n const targetTotalSeconds = targetedLocalTime.getHours() * 3600 + targetedLocalTime.getMinutes() * 60;\n return targetTotalSeconds - localTotalSeconds;\n}\nexport function calculateTimeoutOnCurrentPageConditionDelta(timeonCurrentPageCondition, firstTimeVisitedAt, currentDate) {\n if (timeonCurrentPageCondition.operator === \"after\") {\n const timeDifference = currentDate.getTime() - firstTimeVisitedAt.getTime();\n return timeDifference;\n }\n return 0;\n}\n","import { makeAutoObservable } from \"mobx\";\nimport { getUrl, getWindow, stripPreviewQueryParams } from \"../lib/window\";\nimport { EventEmitter } from \"@/lib/events/eventEmitter\";\n\nexport const PageInfoNamespace = \"pageInfo\" as const;\n\nexport type PageInfoEvents = {\n urlChanged: { url: string };\n};\n\nexport class PageInfo {\n _url: string = \"\";\n events = new EventEmitter(PageInfoNamespace);\n observer!: MutationObserver;\n\n constructor() {\n makeAutoObservable(this);\n\n // Initialize URL\n this.updateUrl(getUrl());\n\n this.setupMutationObserver();\n this.listenEvents();\n this.interceptHistoryMethods();\n }\n\n private setupMutationObserver() {\n this.observer = new MutationObserver(() => {\n this.handleUrlChange();\n });\n this.observer.observe(getWindow().document.body, { childList: true, subtree: true });\n }\n\n private listenEvents() {\n getWindow().addEventListener(\"popstate\", () => {\n this.handleUrlChange();\n });\n getWindow().addEventListener(\"hashchange\", () => {\n this.handleUrlChange.bind(this);\n });\n }\n\n private interceptHistoryMethods() {\n const originalPushState = getWindow().history.pushState;\n const originalReplaceState = getWindow().history.replaceState;\n const handleUrlChange = this.handleUrlChange.bind(this);\n\n getWindow().history.pushState = function (...args: [any, string, (string | URL | null | undefined)?]) {\n originalPushState.apply(this, args);\n handleUrlChange();\n };\n\n getWindow().history.replaceState = function (...args: [any, string, (string | URL | null | undefined)?]) {\n originalReplaceState.apply(this, args);\n handleUrlChange();\n };\n }\n\n private handleUrlChange = () => {\n try {\n const newUrl = getUrl();\n this.updateUrl(newUrl);\n } catch (e) {\n console.error(\"Error updating URL\", { e });\n }\n };\n\n updateUrl(url: string) {\n const currentUrl = this.url;\n this._url = url;\n if (currentUrl !== this.url) {\n this.events.emit(\"urlChanged\", { url: this.url }, { skipGlobal: true });\n }\n }\n\n stop() {\n this.observer.disconnect();\n getWindow().removeEventListener(\"popstate\", this.handleUrlChange);\n getWindow().removeEventListener(\"hashchange\", this.handleUrlChange);\n }\n\n get url() {\n return stripPreviewQueryParams(this._url);\n }\n\n get originalUrl() {\n return this._url;\n }\n}\n\nexport const pageInfo = new PageInfo();\n","import { ElementSearcher, ElementTracker } from \"../element\";\nimport { checkUrlCondition } from \"@common/targeting/audience-check\";\nimport { OnTrackCondition, OnTrackConditions } from \"@common/models/v2\";\nimport { pageInfo } from \"@/stores/PageInfo\";\n\nexport const defaultSearchTimeout = 1000;\n\nexport type OnTrackConditionCheckResult = {\n condition: OnTrackCondition;\n isSatisfied: boolean;\n};\n\nexport type OnTrackConditionCheckResultWithElement = OnTrackConditionCheckResult & { element: Element | null };\n\nexport interface WatchOnTrackConditionsCallbacks {\n onResultChange?: (isOnTrack: boolean) => void;\n onConditionResultChange?: (results: OnTrackConditionCheckResult) => void;\n onTargetElementChange?: (results: OnTrackConditionCheckResultWithElement) => void;\n}\n\nexport function watchOnTrackConditions(\n onTrackConditions: OnTrackConditions,\n { onResultChange, onConditionResultChange, onTargetElementChange }: WatchOnTrackConditionsCallbacks\n) {\n const elementTracker: ElementTracker = new ElementTracker();\n\n let stopUrlWatch: (() => void) | undefined;\n let isSelectorConditionsSatisfied = false;\n let isUrlConditionsSatisfied = false;\n let lastResult: boolean | null = null;\n\n const urlConditions = onTrackConditions.nonEmptyUrlConditions;\n const selectorConditions = onTrackConditions.nonEmptySelectorConditions;\n const selectors = onTrackConditions.selectors;\n\n if (urlConditions.length === 0) {\n isUrlConditionsSatisfied = true;\n }\n\n if (selectorConditions.length === 0) {\n isSelectorConditionsSatisfied = true;\n }\n\n const checkIsOnTrack = () => {\n const isOnTrack = isUrlConditionsSatisfied && isSelectorConditionsSatisfied;\n if (lastResult !== isOnTrack) {\n lastResult = isOnTrack;\n onResultChange?.(isOnTrack);\n }\n\n return isOnTrack;\n };\n\n const notifyConditionResults = (results: OnTrackConditionCheckResult[]) => {\n results.forEach((result) => {\n onConditionResultChange?.(result);\n });\n };\n\n const notifyTargetElementChange = (results: OnTrackConditionCheckResultWithElement[]) => {\n results\n .filter((result) => result.condition.isTargetSelectorCondition())\n .forEach((result) => {\n onTargetElementChange?.(result);\n });\n };\n\n checkIsOnTrack();\n\n const watchSelectorConditions = async () => {\n await elementTracker.trackElements(selectors, (elements) => {\n const results = getSelectorConditionCheckResult(onTrackConditions, elements);\n notifyConditionResults(results);\n notifyTargetElementChange(results);\n\n isSelectorConditionsSatisfied = results.every((result) => result.isSatisfied);\n checkIsOnTrack();\n });\n };\n\n const watchUrlConditions = () => {\n const checkUrlConditions = () => {\n const url = pageInfo.url;\n const results = getUrlConditionCheckResult(onTrackConditions, url);\n notifyConditionResults(results);\n\n isUrlConditionsSatisfied = results.every((result) => result.isSatisfied);\n return checkIsOnTrack();\n };\n\n checkUrlConditions();\n\n stopUrlWatch = pageInfo.events.on(\"urlChanged\", () => {\n checkUrlConditions();\n });\n };\n\n const stop = () => {\n elementTracker.stop();\n stopUrlWatch?.();\n };\n\n watchSelectorConditions();\n watchUrlConditions();\n\n return stop;\n}\n\nexport async function waitForOnTrackConditions(\n onTrackConditions: OnTrackConditions,\n url: string,\n timeout?: number\n): Promise {\n const isOnTrackConditionsEmpty = onTrackConditions.isEmpty();\n const isOnTrackConditionsEnabled = onTrackConditions.isEnabled;\n\n if (isOnTrackConditionsEmpty || !isOnTrackConditionsEnabled) {\n return true;\n }\n\n const isUrlConditionsSatisfied = checkUrlConditions(onTrackConditions, url);\n if (!isUrlConditionsSatisfied) {\n return false;\n }\n\n return waitForSelectorCondition(onTrackConditions, timeout);\n}\n\nexport type OnTrackConditionValidationResult = {\n isUrlConditionsSatisfied: boolean;\n isSelectorConditionsSatisfied: boolean;\n isEmpty: boolean;\n};\n\nfunction checkUrlConditions(onTrackConditions: OnTrackConditions, url: string) {\n const urlConditions = onTrackConditions.nonEmptyUrlConditions;\n const urlConditionCheckResults = urlConditions.map((urlCondition) => {\n return checkUrlCondition(urlCondition, url);\n });\n\n return urlConditionCheckResults.every((result) => result);\n}\n\nfunction getUrlConditionCheckResult(onTrackConditions: OnTrackConditions, url: string) {\n const urlConditions = onTrackConditions.nonEmptyUrlConditions;\n\n return urlConditions.map((urlCondition) => ({\n condition: urlCondition,\n isSatisfied: checkUrlCondition(urlCondition, url),\n }));\n}\n\nfunction getSelectorConditionCheckResult(\n onTrackConditions: OnTrackConditions,\n elements: Record\n) {\n const selectorConditions = onTrackConditions.nonEmptySelectorConditions;\n\n return selectorConditions.map((selectorCondition) => {\n return {\n condition: selectorCondition,\n isSatisfied: !!elements[selectorCondition.right_operand!],\n element: elements[selectorCondition.right_operand!],\n };\n });\n}\n\nasync function waitForSelectorCondition(onTrackConditions: OnTrackConditions, timeout?: number): Promise {\n const elementSearcher = new ElementSearcher();\n const _timeout = timeout ?? defaultSearchTimeout;\n\n const selectorConditions = onTrackConditions.nonEmptySelectorConditions;\n const selectorSearchPromises = selectorConditions.map((selectorCondition) => {\n return elementSearcher.waitForElement(selectorCondition.right_operand!, _timeout);\n });\n const selectorSearchResults = await Promise.all(selectorSearchPromises);\n\n return selectorSearchResults.every((el) => !!el);\n}\n","import { Step } from \"./steps/v2/step\";\n\nexport type TourTrackManagerEvents = {\n wanderedOff: Step;\n targetNotFound: Step;\n trackSatisfied: Step;\n};\n\nexport const TourTrackManagerNamespace = \"tourTrackManager\" as const;\n","import type * as schemas from \"@common/schemas/v2\";\nimport * as models from \"@common/models/v2\";\nimport { BaseStep } from \"./base\";\nimport { StepActions } from \"./step\";\nimport { FlowFlexibility } from \"@common/schemas\";\n\nexport class WaitForElementStep extends BaseStep {\n attributes: models.WaitForElementStepAttributes;\n actions: StepActions;\n\n constructor(step: schemas.Step, actions: StepActions, flowFlexibility: FlowFlexibility) {\n super(step, actions, flowFlexibility);\n this.attributes = new models.WaitForElementStepAttributes(step.attributes as schemas.WaitForElementStepAttributes);\n this.actions = actions;\n }\n\n get isBlockingStepType() {\n return true;\n }\n\n get isTargetableStepType() {\n return true;\n }\n}\n","import { OnTrackConditions } from \"@common/models/v2\";\nimport { Step } from \"./steps/v2/step\";\nimport invariant from \"ts-invariant\";\nimport {\n OnTrackConditionCheckResult,\n OnTrackConditionCheckResultWithElement,\n watchOnTrackConditions,\n} from \"./onTrackConditionCheck\";\nimport { makeAutoObservable, runInAction } from \"mobx\";\nimport { debounce, memoize } from \"lodash-es\";\nimport { EventEmitter } from \"../events/eventEmitter\";\nimport { TourTrackManagerEvents, TourTrackManagerNamespace } from \"./tourTrackManager.events\";\nimport { WaitForElementStep } from \"./steps/v2/waitForElement\";\n\nexport class TourTrackManager {\n events = new EventEmitter(TourTrackManagerNamespace);\n currentStep?: Step;\n detailedResults: Record = {};\n results: Record = {};\n targetElements: Record = {};\n stopWatch?: () => void;\n\n static readonly defaultWanderingOffTimeout = 3000;\n static readonly defaultTargetNotFoundTimeout = 3000;\n\n constructor() {\n makeAutoObservable(this);\n }\n\n setCurrentStep(step: Step) {\n if (step.id === this.currentStep?.id) {\n return;\n }\n\n this.currentStep = step;\n this.watchOnTrackConditions(step);\n }\n\n clearCurrentStep() {\n this.emitLastStatus();\n this.stopWatch?.();\n this.currentStep = undefined;\n }\n\n private watchOnTrackConditions(step: Step) {\n this.stopWatch?.();\n\n const onTrackConditions = step.attributes.onTrackConditions;\n\n this.results[step.id] = false;\n this.detailedResults[step.id] = this.buildInitialDetailedResults(onTrackConditions);\n\n this.stopWatch = watchOnTrackConditions(onTrackConditions, {\n onResultChange: (isOnTrack: boolean) => {\n this.handleResultChange(step, isOnTrack);\n },\n onConditionResultChange: (result: OnTrackConditionCheckResult) => {\n this.handleConditionResultChange(step, result);\n },\n onTargetElementChange: (result: OnTrackConditionCheckResultWithElement) => {\n this.handleTargetElementChange(step, result.element);\n },\n });\n }\n\n private handleResultChange(step: Step, isOnTrack: boolean) {\n runInAction(() => {\n this.results[step.id] = isOnTrack;\n });\n\n this.runOnWanderingOff(step)(() => {\n this.events.emit(\"wanderedOff\", step);\n });\n this.runOnTargetNotFound(step)(() => {\n this.events.emit(\"targetNotFound\", step);\n });\n this.runOnTrackSatisfied(step, () => {\n this.events.emit(\"trackSatisfied\", step);\n });\n }\n\n private handleConditionResultChange(step: Step, result: OnTrackConditionCheckResult) {\n runInAction(() => {\n const detailedResults = this.detailedResults[step.id];\n const index = detailedResults.findIndex((r) => r.condition.id === result.condition.id);\n detailedResults[index] = result;\n });\n }\n\n private handleTargetElementChange(step: Step, element: Element | null) {\n runInAction(() => {\n this.targetElements[step.id] = element;\n });\n }\n\n /**\n * Returns a debounced function that triggers a callback when a user is \"wandering off\"\n * from the current step. The debounce is used to delay the initiation of the wandering\n * off signal, providing a time window for the user to come back on track before the\n * callback is executed. The debounce timeout is dynamically determined based on the step type.\n *\n * Since the debounce timeout is dynamically determined, it is important to not create\n * a new debounce function on every call. `memoize` is used to cache the debounced function\n * per step (identified by `step.id`), ensuring consistent behavior by avoiding redundant\n * debounced function creation.\n */\n private runOnWanderingOff = memoize(\n (step: Step) => {\n return debounce(\n (callback: () => void) => {\n if (this.isEqualToCurrentStep(step.id) && this.isWanderingOff(step.id)) {\n callback();\n }\n },\n this.getWanderingOffTimeout(step),\n { leading: false, trailing: true }\n );\n },\n (step) => step.id\n );\n\n private runOnTargetNotFound = memoize(\n (step: Step) => {\n return debounce(\n (callback: () => void) => {\n if (this.isEqualToCurrentStep(step.id) && this.isTargetNotFound(step.id)) {\n callback();\n }\n },\n this.getTargetNotFoundTimeout(step),\n { leading: false, trailing: true }\n );\n },\n (step) => step.id\n );\n\n private runOnTrackSatisfied = (step: Step, callback: () => void) => {\n if (this.isEqualToCurrentStep(step.id) && this.isOnTrack(step.id)) {\n callback();\n }\n };\n\n private emitLastStatus() {\n const lastStep = this.currentStep;\n if (!lastStep) return;\n\n const isOnTrack = this.isOnTrack(lastStep.id);\n if (isOnTrack) return;\n\n const isTargetNotFound = this.isTargetNotFound(lastStep.id);\n if (isTargetNotFound) {\n this.events.emit(\"targetNotFound\", lastStep);\n return;\n }\n\n const isWanderingOff = this.isWanderingOff(lastStep.id);\n if (isWanderingOff) {\n this.events.emit(\"wanderedOff\", lastStep);\n }\n }\n\n isOnTrack(stepId: string) {\n return this.results[stepId];\n }\n\n isWanderingOff(stepId: string) {\n return !this.isOnCorrectPage(stepId);\n }\n\n isTargetNotFound(stepId: string) {\n const isOnCorrectPage = this.isOnCorrectPage(stepId);\n const isTargetElementAvailable = this.isTargetElementAvailable(stepId);\n return isOnCorrectPage && !isTargetElementAvailable;\n }\n\n getTargetElement(stepId: string) {\n if (!this.isOnTrack(stepId)) {\n return null;\n }\n return this.targetElements[stepId];\n }\n\n stop() {\n this.stopWatch?.();\n }\n\n private isOnCorrectPage(stepId: string) {\n const result = this.mustGetResult(stepId);\n if (result) {\n return true;\n }\n\n const detailedResults = this.mustGetDetailedResult(stepId);\n\n const urlConditions = detailedResults.filter((r) => r.condition.isUrlCondition());\n const supplementarySelectorConditions = detailedResults.filter((r) =>\n r.condition.isSupplementarySelectorCondition()\n );\n const pageOnTrackConditions = urlConditions.concat(supplementarySelectorConditions);\n\n return pageOnTrackConditions.every((r) => r.isSatisfied);\n }\n\n private isTargetElementAvailable(stepId: string) {\n const result = this.mustGetResult(stepId);\n if (result) {\n return true;\n }\n\n const detailedResults = this.mustGetDetailedResult(stepId);\n\n const targetElementConditions = detailedResults.filter((r) => r.condition.isTargetSelectorCondition());\n\n return targetElementConditions.every((r) => r.isSatisfied);\n }\n\n getResult(stepId: string) {\n return this.results[stepId];\n }\n\n getDetailedResult(stepId: string) {\n return this.detailedResults[stepId];\n }\n\n private getWanderingOffTimeout(step: Step) {\n if (step instanceof WaitForElementStep) {\n return step.attributes.timeout;\n }\n\n return TourTrackManager.defaultWanderingOffTimeout;\n }\n\n private getTargetNotFoundTimeout(step: Step) {\n if (step instanceof WaitForElementStep) {\n return step.attributes.timeout;\n }\n\n return TourTrackManager.defaultTargetNotFoundTimeout;\n }\n\n private mustGetResult(stepId: string) {\n const result = this.getResult(stepId);\n invariant(result !== undefined, \"step on track conditions not checked yet\");\n\n return result;\n }\n\n private mustGetDetailedResult(stepId: string) {\n const detailedResult = this.getDetailedResult(stepId);\n invariant(detailedResult !== undefined, \"step on track conditions not checked yet\");\n\n return detailedResult;\n }\n\n private isEqualToCurrentStep(stepId: string) {\n return this.currentStep?.id === stepId;\n }\n\n private buildInitialDetailedResults(onTrackConditions: OnTrackConditions) {\n return onTrackConditions.nonEmptyConditions.map((condition) => ({ condition, isSatisfied: false }));\n }\n}\n","import { assign, createActor, enqueueActions, setup } from \"xstate\";\nimport { fromStream } from \"mobx-utils\";\nimport { Step } from \"../steps/v2/step\";\nimport { Flow, FlowPosition, FlowState, Section } from \"./types\";\nimport { FlowFlexibility } from \"@common/schemas\";\n\nexport interface FlowStateMachineInput {\n flow: Flow;\n flowFlexibility: FlowFlexibility;\n initialFlowState: FlowState;\n}\n\nexport interface FlowStateMachineContext extends FlowPosition {\n flow: Flow;\n flowFlexibility: FlowFlexibility;\n currentTime: number;\n eventQueue: FlowStateMachineEvent[];\n}\n\nconst getFlowPosition = (context: FlowStateMachineContext): FlowPosition => ({\n currentSectionIndex: context.currentSectionIndex,\n currentStepIndex: context.currentStepIndex,\n flowKey: context.flow.key,\n});\n\nexport interface FlowStateMachineHooks {\n onStepTransition?: (pos: FlowPosition, step: Step) => void;\n onWaitBlockingStep?: (pos: FlowPosition, step: Step) => void;\n onSectionTransition?: (pos: FlowPosition, section: Section) => void;\n onFlowFinish?: () => void;\n onStepRun?: (pos: FlowPosition, step: Step) => void;\n onStepDispose?: (pos: FlowPosition, step: Step) => void;\n}\n\nexport interface CreateFlowStateActorParams {\n input: FlowStateMachineInput;\n hooks?: FlowStateMachineHooks;\n}\n\ntype FlowStateMachineEvent =\n | { type: \"unblock\" }\n | { type: \"mediaFinished\" }\n | { type: \"timeUpdate\"; currentTime: number }\n | { type: \"mediaPlaying\" }\n | { type: \"replay\" };\n\nexport const createFlowStateActor = ({ input, hooks }: CreateFlowStateActorParams) => {\n const flowStateMachine = setup({\n types: {\n input: {} as FlowStateMachineInput,\n context: {} as FlowStateMachineContext,\n events: {} as FlowStateMachineEvent,\n },\n guards: {\n isLastSection: ({ context }) => {\n const { currentSectionIndex, flow } = context;\n return currentSectionIndex === flow.sections.length - 1;\n },\n isStepRunTime: ({ context }) => {\n const { currentSectionIndex, currentStepIndex, flow, currentTime } = context;\n const section = flow.sections[currentSectionIndex];\n const step = section.steps[currentStepIndex];\n return currentTime >= step.start;\n },\n isStepEndTime: ({ context }) => {\n const { currentSectionIndex, currentStepIndex, flow, currentTime } = context;\n const section = flow.sections[currentSectionIndex];\n const step = section.steps[currentStepIndex];\n return currentTime >= step.end;\n },\n hasNextStep: ({ context }) => {\n const { currentSectionIndex, currentStepIndex, flow } = context;\n const section = flow.sections[currentSectionIndex];\n return currentStepIndex < section.steps.length - 1;\n },\n isLastStepInSection: ({ context }) => {\n const { currentSectionIndex, currentStepIndex, flow } = context;\n const section = flow.sections[currentSectionIndex];\n return currentStepIndex === section.steps.length - 1;\n },\n isBlockingStep: ({ context }) => {\n const { currentSectionIndex, currentStepIndex, flow } = context;\n const section = flow.sections[currentSectionIndex];\n const step = section.steps[currentStepIndex];\n return step.isBlocking;\n },\n },\n actions: {\n proceedNextSection: assign(({ context }) => {\n const { currentSectionIndex } = context;\n const nextSectionPosition = { sectionIndex: currentSectionIndex + 1, stepIndex: 0 };\n const section = context.flow.sections[nextSectionPosition.sectionIndex];\n hooks?.onSectionTransition?.(getFlowPosition(context), section);\n return {\n ...context,\n currentSectionIndex: nextSectionPosition.sectionIndex,\n currentStepIndex: nextSectionPosition.stepIndex,\n currentTime: 0,\n };\n }),\n proceedNextStep: assign(({ context }) => {\n const { currentSectionIndex, currentStepIndex, flow } = context;\n const section = flow.sections[currentSectionIndex];\n\n if (currentStepIndex < section.steps.length - 1) {\n return { ...context, currentStepIndex: currentStepIndex + 1 };\n }\n\n return context;\n }),\n setCurrentTime: assign(({ context, event }) => {\n if (event.type === \"timeUpdate\") {\n return { ...context, currentTime: event.currentTime };\n }\n return context;\n }),\n deferMediaFinishedEvent: assign({\n eventQueue: ({ context: { eventQueue }, event }) => [...eventQueue, event],\n }),\n drainDeferredMediaFinishedEvents: enqueueActions(({ context: { eventQueue }, enqueue }) => {\n eventQueue.forEach((event) => enqueue.raise(event));\n enqueue.assign({ eventQueue: [] });\n }),\n // hooks\n initStep: ({ context }) => {\n const step = context.flow.sections[context.currentSectionIndex].steps[context.currentStepIndex];\n hooks?.onStepTransition?.(getFlowPosition(context), step);\n step.init();\n },\n runStep: ({ context }) => {\n const step = context.flow.sections[context.currentSectionIndex].steps[context.currentStepIndex];\n step.run();\n hooks?.onStepRun?.(getFlowPosition(context), step);\n },\n finishStep: ({ context }) => {\n const step = context.flow.sections[context.currentSectionIndex].steps[context.currentStepIndex];\n step.finish();\n },\n disposeStep: ({ context }) => {\n const step = context.flow.sections[context.currentSectionIndex].steps[context.currentStepIndex];\n step.dispose();\n hooks?.onStepDispose?.(getFlowPosition(context), step);\n },\n finish: () => {\n hooks?.onFlowFinish?.();\n },\n waitBlockingStep: ({ context }) => {\n const step = context.flow.sections[context.currentSectionIndex].steps[context.currentStepIndex];\n hooks?.onWaitBlockingStep?.(getFlowPosition(context), step);\n },\n },\n }).createMachine({\n /** @xstate-layout N4IgpgJg5mDOIC5QDMA2B7A7gZQC4ENcwBiXASwFswBVABwkLAG0AGAXUVFvVjPPQB2nEAA9EARnEAWAJwA6ABxTxClgFZxagOzaAzFIA0IAJ4SFuxeekspu6bq0OAvk6NoseRnMz4+ZAVAAkgJ++KgAKpQ09IykUXQMRKwcSCDcvPxCqWII4jJaCnIATLa6arosWiwqRqYIALRaTXIy9hVqLEVdugoubhg4BERysES0waGoZABe-lDEycLpfoLCOUXVAGxyLCw9HZtayo5FtYj1Uo7FTVLqmjI9UkV9IO6DXqNgtACCAMbkADcSItUstMmtEBtNHJDuImjZOroSlozg0SlI5HDNixNnoZGoitoXm9PMNfgALMC-ADWeC+ACUAK4CSJUBbsJY8FZZUA5PKbQpwuFPAVPB7iVH1OyYp7iTb6cTVMqdTbEgaksByClU2ljJksqILcQpLhc8HZSGE+S3ZQdXStAVqSXS6RFOUKpUdIqq1yvdVDTU+PwBABi6AATvrWSRyFQEowQaaMmRVhaEF01Go5BoyloZAoShV1JKis11BsC9ItCU1GqPAGRnrmSEAuyTWkzSmeaJIdUs4dtPkCgKbDJUUUZPIlOU1LdMxOuj7+vWPnr8AI25zk6neb3oQPHHKZFJZKXUeVCk10XndJtNJ06+9hkHyKGIwBRAQQaNxOMxJIcqCnY7j26Z2FomL3h0J7ynCqJSEoMrYkUBZSLO3o6I+GpapSNJ0rQn7foaiYdtu3Z8jIhwwlocJqJsuJunkqJNNsdhqPmCiKgoDz6FhDbanhYyET+TDGlu3IQmBbo7OouKinsCgKMxWisfcilcTxUh8auXwhv4ZCwOScybkBZGSVC2y7D0JTiEUPSKboqKSIpMJ0SpJSqDRLC9L6JINi+ABCGA0nM+HEMyABGwXUiRYJduZVk7Kod5KLKuJOdiFjVFUmzioedHac+vi4EF6AhQEYXhl8qD4MYsXAeRkJ0VmtmUbemiaDRTomBIFQQbe+biA4KkdJIhWBsVpXlVAYVUBAZD4HpISGZA9VmWmGbbIquj6Pi3F5sWPW5LILCYjiDzeQoo0FON3iTdFoVjCZSYSWmR5FIoTzIgoNGSBKR0dVmlS2OxmaUd5S5+iuRV8FN1KPV8RrtnFIF8jlci2Ni0jytWGgogDmwnnI9rej0cJtbdny0AAwugFC0KgYCvvMa2vbuuT5BitoVMenPyk5+IWJxPRNPajqyJTYy0-TjPM0j4nmuzdlSJZdGlvk+aXP9dR5OUihDT9jiUVdta+f6Xi0OGZVgJAcwAHJgCIuBhaziugdjGKuopE76A4O3jpUEHqBrJMnqoui3S+YbhgAsrbi36YZxBzQtS0GZSECu-FG1IqdlEaAomyk5O+N1F0RzZuYrSlN6imR8V0dx-NCfLeSyfx2nK2Z2Jpls6BtcfUXEM6GoV1wUdGbiIoRd0Tt9GEz6voCOgEBwMIfmMAr2fs9IcoyihBYPLYjiOUd9SURiVTqNxd6zkNkMbzDzMTOQYTRvGRBb6jEjHh93EqG6VoMgNiyElIbYmLFvQqEkCNSWXwX4LSmLMAIX9GocyuPkQks4CR5DHGfW+xRuLeX5LlbiMg4E-H+GQIEqDJK4IxFdPMmU7BH2dHROQ7l9ACnlNiTMt0BK6gZMyaMtC3ptUxK0BccJvT5klENKejgjgFHxOdPMptlxPgmsGKA0coxRFEUrGyxMJz4nzASCcaE5HSkUZcbiBwNY+Q0dhKm+oWxQAMe7fIFg7J7HojYRwtinJ7GzNApEKE9gyE6OQs20NNQuPXB49YiVuJWFxF1Momx4LQkVJUPGk46LeS0jEzRd1tHR2Evo3ubt1gVA+kcW4gCWLcVRPKeQyEuE7VLEXfhuFBEES-CIqp29PHyhkoSIa5YBQ9BafaGEiIVadPcuIChncjIoKGd-dBWYdBPEqDxasDxUSaxaOUTouw0Ig2iU4-y90yrwwqmMRJP8qiYhUpOZEuVDhKQBreQoCFC4TmxCrABFDpYMyZnMJ5HMCQwmkexXYuIeJOSOFmTi9EdD5EUrY26ltra2wCA7J2+EoW6w+iwC+pZbjeXYqfMu5KIIPELseWQc58j1z4I3DuidyRQq6IXFo5KQGpOAd1OlFdygOGxDww4OJbrIG5ZAXlDhUUPHnDRO8exxwninneHadgBQOj4S4JwQA */\n id: \"flowState\",\n initial: \"waitInitialPlay\",\n context: ({ input }) => ({\n flowFlexibility: input.flowFlexibility,\n currentTime: input.initialFlowState.currentTime,\n currentSectionIndex: input.initialFlowState.currentSectionIndex,\n currentStepIndex: input.initialFlowState.currentStepIndex,\n flow: input.flow,\n eventQueue: [],\n flowKey: input.flow.key,\n }),\n on: {\n timeUpdate: {\n actions: \"setCurrentTime\",\n },\n },\n\n states: {\n waitInitialPlay: {\n on: {\n mediaPlaying: {\n target: \"stepInitializing\",\n },\n },\n },\n\n waitingInitialTimeUpdate: {\n on: {\n timeUpdate: {\n actions: \"setCurrentTime\",\n target: \"stepInitializing\",\n },\n },\n },\n\n stepInitializing: {\n entry: \"initStep\",\n always: {\n target: \"stepActive\",\n },\n },\n\n stepActive: {\n always: [\n {\n target: \"checkStepRunTime\",\n },\n ],\n },\n\n checkStepRunTime: {\n always: [\n {\n guard: \"isStepRunTime\",\n target: \"stepRunning\",\n },\n {\n target: \"waitingForRunTime\",\n },\n ],\n },\n\n waitingForRunTime: {\n on: {\n timeUpdate: [\n {\n actions: \"setCurrentTime\",\n target: \"checkStepRunTime\",\n },\n ],\n },\n },\n\n stepRunning: {\n entry: \"runStep\",\n always: {\n target: \"stepRan\",\n },\n },\n\n stepRan: {\n always: [\n {\n target: \"checkStepEndTime\",\n },\n ],\n },\n\n waitingForEndTime: {\n on: {\n timeUpdate: [\n {\n actions: \"setCurrentTime\",\n target: \"checkStepEndTime\",\n },\n ],\n },\n },\n\n checkStepEndTime: {\n always: [\n {\n guard: \"isStepEndTime\",\n target: \"stepFinishing\",\n },\n {\n target: \"waitingForEndTime\",\n },\n ],\n },\n\n stepFinishing: {\n entry: \"finishStep\",\n always: {\n target: \"waitBlockingStep\",\n },\n },\n\n waitBlockingStep: {\n always: [\n {\n guard: \"isBlockingStep\",\n actions: \"waitBlockingStep\",\n },\n {\n target: \"stepCompleting\",\n },\n ],\n on: {\n replay: {\n target: \"stepInitializing\",\n },\n mediaFinished: {\n description:\n \"Media finished event can be dispatched when there is a blocking step at the end of the section. We should defer this event to handle it later.\",\n actions: \"deferMediaFinishedEvent\",\n },\n },\n },\n\n stepCompleting: {\n entry: \"disposeStep\",\n always: [\n {\n guard: \"hasNextStep\",\n target: \"proceedingNextStep\",\n },\n {\n guard: \"isLastStepInSection\",\n target: \"waitForMediaFinish\",\n },\n ],\n },\n\n proceedingNextStep: {\n always: {\n actions: \"proceedNextStep\",\n target: \"stepInitializing\",\n },\n },\n\n waitForMediaFinish: {\n description: \"\",\n entry: \"drainDeferredMediaFinishedEvents\",\n on: {\n mediaFinished: [\n {\n guard: \"isLastSection\",\n target: \"finished\",\n },\n {\n actions: \"proceedNextSection\",\n target: \"waitingInitialTimeUpdate\",\n },\n ],\n },\n },\n\n finished: {\n entry: \"finish\",\n type: \"final\",\n },\n },\n });\n\n return createActor(flowStateMachine, { input });\n};\n\nexport const createFlowStateStream = (machine: ReturnType) => fromStream(machine);\n","import { EmptyPayload } from \"@/lib/events/types\";\nimport { Checkpoint } from \"./types\";\nimport { Step } from \"../steps/v2/step\";\n\nexport type TourPlaybackManagerEvents = {\n questionChoiceSelected: { choiceId: string; choiceType: string };\n avatarCaptionClicked: { status: boolean };\n avatarMuteClicked: { status: boolean };\n unsuspended: EmptyPayload;\n checkpointSaved: { checkpoint: Checkpoint };\n checkpointLoaded: EmptyPayload;\n finished: EmptyPayload;\n terminated: EmptyPayload;\n initialized: EmptyPayload;\n started: EmptyPayload;\n suspended: EmptyPayload;\n dismissed: EmptyPayload;\n tourSwitched: { guideId: string };\n stepTransitioned: { step: Step };\n sectionTransitioned: EmptyPayload;\n stepExecuted: EmptyPayload;\n stepDisposed: EmptyPayload;\n flowStarted: EmptyPayload;\n flowFinished: EmptyPayload;\n targetElementNotFound: EmptyPayload;\n userWanderedOff: EmptyPayload;\n targetElementHighlighted: EmptyPayload;\n targetElementChanged: { currentTarget: string | null; nextTarget: string | null };\n stepFinished: EmptyPayload;\n willStartFlow: { fromTime: number; autoPlay: boolean };\n introStartTourClicked: EmptyPayload;\n introCloseTourClicked: EmptyPayload;\n introPostponeTourClicked: EmptyPayload;\n finishCriteriaMet: EmptyPayload;\n userEngaged: EmptyPayload;\n feedbackClicked: EmptyPayload;\n};\n\nexport type TourPlaybackEventContext = {\n stepId: string;\n stepIndex: number;\n stepOrder: number;\n stepType: string;\n isCheckpoint: boolean;\n totalSteps: number;\n totalSectionSteps: number;\n totalSections: number;\n tourProgress: number;\n flowKey: string;\n currentMediaDuration: number;\n tourPlaybackVersion: string;\n sectionIndex: number;\n time: number;\n startedAt?: number;\n sessionId: string;\n};\n\nexport const TourPlaybackNamespace = \"tourPlayback\" as const;\n","import type * as schemas from \"@common/schemas/v2\";\nimport * as models from \"@common/models/v2\";\nimport { BaseStep } from \"./base\";\nimport { StepActions } from \"./step\";\nimport { FlowFlexibility } from \"@common/schemas\";\n\nexport class FillerStep extends BaseStep {\n attributes: models.FillerStepAttributes;\n actions: StepActions;\n\n constructor(step: schemas.Step, actions: StepActions, flowFlexibility: FlowFlexibility) {\n super(step, actions, flowFlexibility);\n this.attributes = new models.FillerStepAttributes(step.attributes as schemas.FillerStepAttributes);\n this.actions = actions;\n }\n}\n","import * as models from \"@common/models/v2\";\nimport type * as schemas from \"@common/schemas/v2\";\nimport { BaseStep } from \"./base\";\nimport { StepActions } from \"./step\";\nimport { makeObservable, observable, override } from \"mobx\";\nimport { FlowFlexibility } from \"@common/schemas\";\n\nexport class UserClickStep extends BaseStep {\n attributes: models.UserClickStepAttributes;\n actions: StepActions;\n\n target?: Element | null;\n isClicked: boolean = false;\n stopTrackingTargetElement?: () => void;\n\n constructor(step: schemas.Step, actions: StepActions, flowFlexibility: FlowFlexibility) {\n super(step, actions, flowFlexibility);\n\n this.attributes = new models.UserClickStepAttributes(step.attributes as schemas.UserClickStepAttributes);\n this.actions = actions;\n makeObservable(this, {\n isClicked: observable,\n isBlocking: override,\n });\n }\n\n async run() {\n super.run();\n this.isClicked = false;\n this.trackTargetElement();\n }\n\n private trackTargetElement() {\n this.stopTrackingTargetElement?.();\n this.stopTrackingTargetElement = this.actions.onTargetElementChange(\n this.id,\n this.handleTargetElementChange.bind(this)\n );\n }\n\n private handleTargetElementChange(targetElement: Element | null) {\n this.target?.removeEventListener(this.attributes.clickDetectionMethod, this.handleInteractionClick, true);\n\n this.target = targetElement;\n this.target?.addEventListener(this.attributes.clickDetectionMethod, this.handleInteractionClick, true);\n this.actions.setCurrentTargetElement(targetElement);\n }\n\n dispose() {\n super.dispose();\n this.stopTrackingTargetElement?.();\n this.stopTrackingTargetElement = undefined;\n this.target?.removeEventListener(this.attributes.clickDetectionMethod, this.handleInteractionClick, true);\n this.target = undefined;\n this.actions.setCurrentTargetElement(undefined);\n }\n\n handleInteractionClick = (e: Event) => {\n this.isClicked = true;\n };\n\n get additionalContent() {\n return this.attributes?.additionalContent;\n }\n\n get isBlocking() {\n return !this.isClicked;\n }\n\n get isBlockingStepType() {\n return true;\n }\n\n get isTargetableStepType() {\n return true;\n }\n\n get skipStepOnEarlyUnblock() {\n return true;\n }\n}\n","import * as models from \"@common/models/v2\";\nimport type * as schemas from \"@common/schemas/v2\";\nimport { BaseStep } from \"./base\";\nimport { StepActions } from \"./step\";\nimport { computed, makeObservable, observable, override } from \"mobx\";\nimport { FlowFlexibility } from \"@common/schemas\";\n\nexport class DragStep extends BaseStep {\n attributes: models.DragStepAttributes;\n actions: StepActions;\n\n target?: Element | null;\n state: \"pending\" | \"dragging\" | \"dragEnded\" | \"idle\" = \"idle\";\n isDragging: boolean = false;\n stopTrackingTargetElement?: () => void;\n\n constructor(step: schemas.Step, actions: StepActions, flowFlexibility: FlowFlexibility) {\n super(step, actions, flowFlexibility);\n\n this.attributes = new models.DragStepAttributes(step.attributes as schemas.DragStepAttributes);\n this.actions = actions;\n makeObservable(this, {\n isDragging: observable,\n isBlocking: override,\n isBlockingStepType: computed,\n isTargetableStepType: computed,\n state: observable,\n });\n }\n\n async run() {\n super.run();\n this.trackTargetElement();\n }\n\n private trackTargetElement() {\n this.stopTrackingTargetElement?.();\n this.stopTrackingTargetElement = this.actions.onTargetElementChange(\n this.id,\n this.handleTargetElementChange.bind(this)\n );\n }\n\n private handleTargetElementChange(targetElement: Element | null) {\n this.target?.removeEventListener(\"mousedown\", this.onMouseDown);\n this.target?.removeEventListener(\"mousemove\", this.onDragStart);\n this.target?.removeEventListener(\"mouseup\", this.onDragEnd);\n this.target?.removeEventListener(\"dragend\", this.onDragEnd);\n\n this.target = targetElement;\n this.target?.addEventListener(\"mousedown\", this.onMouseDown);\n this.target?.addEventListener(\"mousemove\", this.onDragStart);\n this.target?.addEventListener(\"mouseup\", this.onDragEnd);\n this.target?.addEventListener(\"dragend\", this.onDragEnd);\n\n this.actions.setCurrentTargetElement(targetElement);\n }\n\n dispose() {\n super.dispose();\n this.state = \"idle\";\n this.stopTrackingTargetElement?.();\n this.stopTrackingTargetElement = undefined;\n this.target?.removeEventListener(\"mousedown\", this.onMouseDown);\n this.target?.removeEventListener(\"mousemove\", this.onDragStart);\n this.target?.removeEventListener(\"mouseup\", this.onDragEnd);\n this.target?.removeEventListener(\"dragend\", this.onDragEnd);\n this.target = undefined;\n this.actions.setCurrentTargetElement(undefined);\n }\n\n onMouseDown = (e: Event) => {\n if (this.state !== \"idle\") return;\n this.state = \"pending\";\n this.isDragging = false;\n };\n\n onDragStart = (e: Event) => {\n if (this.state !== \"pending\") return;\n this.state = \"dragging\";\n this.isDragging = true;\n };\n\n onDragEnd = (e: Event) => {\n if (this.state !== \"dragging\") return;\n this.state = \"dragEnded\";\n this.isDragging = false;\n };\n\n get isBlocking() {\n return this.state !== \"dragEnded\";\n }\n\n get isBlockingStepType() {\n return true;\n }\n\n get isTargetableStepType() {\n return true;\n }\n}\n","import type * as schemas from \"@common/schemas/v2\";\nimport * as models from \"@common/models/v2\";\nimport { BaseStep } from \"./base\";\nimport { StepActions } from \"./step\";\nimport { FlowFlexibility } from \"@common/schemas\";\n\nexport class HighlightStep extends BaseStep {\n attributes: models.HighlightStepAttributes;\n actions: StepActions;\n\n target?: Element | null;\n stopTrackingTargetElement?: () => void;\n\n constructor(step: schemas.Step, actions: StepActions, flowFlexibility: FlowFlexibility) {\n super(step, actions, flowFlexibility);\n\n this.attributes = new models.HighlightStepAttributes(step.attributes as schemas.HighlightStepAttributes);\n this.actions = actions;\n }\n\n async run() {\n super.run();\n this.trackTargetElement();\n }\n\n private trackTargetElement() {\n this.stopTrackingTargetElement?.();\n this.stopTrackingTargetElement = this.actions.onTargetElementChange(\n this.id,\n this.handleTargetElementChange.bind(this)\n );\n }\n\n private handleTargetElementChange(targetElement: Element | null) {\n if (!this.isFinished) {\n this.target = targetElement;\n this.actions.setCurrentTargetElement(targetElement);\n }\n }\n\n async finish() {\n super.finish();\n this.isFinished = true;\n }\n\n dispose() {\n super.dispose();\n this.stopTrackingTargetElement?.();\n this.stopTrackingTargetElement = undefined;\n this.target = undefined;\n this.actions.setCurrentTargetElement(undefined);\n }\n\n get additionalContent() {\n return this.attributes?.additionalContent;\n }\n\n get isTargetableStepType() {\n return true;\n }\n}\n","import type * as schemas from \"@common/schemas/v2\";\nimport * as models from \"@common/models/v2\";\nimport { BaseStep } from \"./base\";\nimport { StepActions } from \"./step\";\nimport { FlowFlexibility } from \"@common/schemas\";\n\nexport class ShowContentStep extends BaseStep {\n attributes: models.ShowContentStepAttributes;\n actions: StepActions;\n\n constructor(step: schemas.Step, actions: StepActions, flowFlexibility: FlowFlexibility) {\n super(step, actions, flowFlexibility);\n this.attributes = new models.ShowContentStepAttributes(step.attributes as schemas.ShowContentStepAttributes);\n this.actions = actions;\n }\n\n get additionalContent() {\n return this.attributes.content;\n }\n}\n","import * as models from \"@common/models/v2\";\nimport type * as schemas from \"@common/schemas/v2\";\nimport { BaseStep } from \"./base\";\nimport { ElementTextWriter } from \"@/lib/element\";\nimport { StepActions } from \"./step\";\nimport { Deferred } from \"@/lib/Deferred\";\nimport { makeObservable, observable, override } from \"mobx\";\nimport { FlowFlexibility } from \"@common/schemas\";\n\nexport class AutoTypeStep extends BaseStep {\n attributes: models.AutoTypeStepAttributes;\n actions: StepActions;\n\n target?: Element | null;\n isTyped: boolean = false;\n elementWriter: ElementTextWriter;\n deferredElementFound: Deferred | null = null;\n stopTrackingTargetElement?: () => void;\n\n constructor(step: schemas.Step, actions: StepActions, flowFlexibility: FlowFlexibility) {\n super(step, actions, flowFlexibility);\n this.attributes = new models.AutoTypeStepAttributes(step.attributes as schemas.AutoTypeStepAttributes);\n this.actions = actions;\n this.elementWriter = new ElementTextWriter();\n makeObservable(this, {\n isTyped: observable,\n isBlocking: override,\n });\n }\n\n async init() {\n super.init();\n this.isTyped = false;\n this.deferredElementFound = new Deferred();\n\n this.stopTrackingTargetElement?.();\n this.trackTargetElement();\n }\n\n private trackTargetElement() {\n this.stopTrackingTargetElement?.();\n this.stopTrackingTargetElement = this.actions.onTargetElementChange(\n this.id,\n this.handleTargetElementChange.bind(this)\n );\n }\n\n private handleTargetElementChange(targetElement: Element | null) {\n if (!targetElement) {\n return;\n }\n\n this.target = targetElement;\n this.actions.setCurrentTargetElement(targetElement);\n this.deferredElementFound?.resolve(targetElement);\n }\n\n async finish() {\n super.finish();\n await this.write(this.attributes.text);\n }\n\n dispose(): void {\n super.dispose();\n\n this.stopTrackingTargetElement?.();\n this.stopTrackingTargetElement = undefined;\n this.target = undefined;\n this.actions.setCurrentTargetElement(undefined);\n }\n\n private async write(text: string) {\n if (this.deferredElementFound) {\n await this.deferredElementFound?.promise;\n }\n\n if (!this.target) {\n return;\n }\n\n await this.elementWriter.writeText(this.target as HTMLInputElement, text, this.attributes.instantPaste);\n this.isTyped = true;\n }\n\n get isBlocking() {\n return !this.isTyped;\n }\n\n get isBlockingStepType() {\n return true;\n }\n\n get isTargetableStepType() {\n return true;\n }\n}\n","import * as models from \"@common/models/v2\";\nimport type * as schemas from \"@common/schemas/v2\";\nimport { BaseStep } from \"./base\";\nimport { ElementClicker, ElementTracker } from \"@/lib/element\";\nimport { StepActions } from \"./step\";\nimport { makeObservable, observable, override } from \"mobx\";\nimport { FlowFlexibility } from \"@common/schemas\";\n\nexport class AutoClickStep extends BaseStep {\n attributes: models.AutoClickStepAttributes;\n actions: StepActions;\n\n target?: Element | null;\n isClicked = false;\n elementClicker: ElementClicker;\n elementTracker?: ElementTracker;\n stopTrackingTargetElement?: () => void;\n\n constructor(step: schemas.Step, actions: StepActions, flowFlexibility: FlowFlexibility) {\n super(step, actions, flowFlexibility);\n this.attributes = new models.AutoClickStepAttributes(step.attributes as schemas.AutoClickStepAttributes);\n this.actions = actions;\n this.elementClicker = new ElementClicker();\n makeObservable(this, {\n isClicked: observable,\n isBlocking: override,\n });\n }\n\n async run() {\n super.run();\n this.isClicked = false;\n this.trackTargetElement();\n }\n\n private trackTargetElement() {\n this.stopTrackingTargetElement?.();\n this.stopTrackingTargetElement = this.actions.onTargetElementChange(\n this.id,\n this.handleTargetElementChange.bind(this)\n );\n }\n\n private handleTargetElementChange(targetElement: Element | null) {\n this.target = targetElement;\n this.actions.setCurrentTargetElement(targetElement);\n }\n\n async finish() {\n super.finish();\n await this.clickElement(this.attributes.targetElementSelector);\n }\n\n dispose(): void {\n super.dispose();\n this.stopTrackingTargetElement?.();\n this.stopTrackingTargetElement = undefined;\n this.elementTracker?.stop();\n this.target = undefined;\n this.actions.setCurrentTargetElement(undefined);\n }\n\n // Why not accept the element as a parameter directly?\n private async clickElement(selector: string) {\n if (!this.isClicked) {\n await this.elementClicker.clickElement(selector);\n this.elementTracker?.stop();\n this.isClicked = true;\n }\n }\n\n get isBlocking() {\n return !this.isClicked;\n }\n\n get isBlockingStepType() {\n return true;\n }\n\n get isTargetableStepType() {\n return true;\n }\n}\n","import type * as schemas from \"@common/schemas/v2\";\nimport * as models from \"@common/models/v2\";\nimport { BaseStep } from \"./base\";\nimport { StepActions } from \"./step\";\nimport { autorun, computed, makeObservable, observable, override, reaction, runInAction } from \"mobx\";\nimport { FlowFlexibility } from \"@common/schemas\";\n\nexport class SleepStep extends BaseStep {\n attributes: models.SleepStepAttributes;\n actions: StepActions;\n duration: number = 0;\n isWaiting: boolean = false;\n isTimedout: boolean = false;\n\n constructor(step: schemas.Step, actions: StepActions, flowFlexibility: FlowFlexibility) {\n super(step, actions, flowFlexibility);\n this.attributes = new models.SleepStepAttributes(step.attributes as schemas.SleepStepAttributes);\n this.actions = actions;\n this.duration = this.attributes.duration;\n this.isTimedout = false;\n makeObservable(this, {\n isWaiting: observable,\n isTimedout: observable,\n isBlocking: override,\n });\n }\n\n async run() {\n super.run();\n if (!this.isWaiting) {\n this.isWaiting = true;\n\n const sleep = new Promise((resolve) => setTimeout(resolve, this.duration));\n sleep.then(() => {\n runInAction(() => {\n this.isWaiting = false;\n });\n });\n }\n }\n\n get isBlocking() {\n return this.isWaiting;\n }\n\n get isBlockingStepType() {\n return true;\n }\n}\n","import type * as schemas from \"@common/schemas/v2\";\nimport * as models from \"@common/models/v2\";\nimport { BaseStep } from \"./base\";\nimport { StepActions } from \"./step\";\nimport { getCurrentPath, navigateToPath } from \"@/lib/window\";\nimport { FlowFlexibility } from \"@common/schemas\";\n\nexport class RedirectStep extends BaseStep {\n attributes: models.RedirectStepAttributes;\n actions: StepActions;\n\n constructor(step: schemas.Step, actions: StepActions, flowFlexibility: FlowFlexibility) {\n super(step, actions, flowFlexibility);\n this.attributes = new models.RedirectStepAttributes(step.attributes as schemas.RedirectStepAttributes);\n this.actions = actions;\n }\n\n async run() {\n super.run();\n if (this.attributes.slug && this.attributes.changeType === \"redirect\") {\n this.switchByRoute(this.attributes.slug);\n }\n }\n\n private switchByRoute(path: string) {\n const currentPath = getCurrentPath();\n const newRoute = this.parseRoutePattern(path);\n\n if (newRoute !== currentPath) {\n navigateToPath(newRoute);\n }\n }\n\n private parseRoutePattern = (path: string) => {\n const currentPath = getCurrentPath();\n const currentRoutes = currentPath.split(\"/\");\n\n return path\n .split(\"/\")\n .map((r, index) => (r === \"*\" ? currentRoutes[index] : r))\n .join(\"/\");\n };\n\n get isBlockingStepType() {\n return false;\n }\n\n // TODO: discuss the risk of trusting on the execution of the last step before reload with Ashish\n get isBlocking() {\n return false;\n }\n}\n","import type * as schemas from \"@common/schemas/v2\";\nimport { FillerStep } from \"./filler\";\nimport { UserClickStep } from \"./userClick\";\nimport { DragStep } from \"./drag\";\nimport { HighlightStep } from \"./highlight\";\nimport { QuestionFactory, QuestionStep } from \"./question\";\nimport { ShowContentStep } from \"./showContent\";\nimport { ModalFactory, ModalStep } from \"./modal\";\nimport { WaitForElementStep } from \"./waitForElement\";\nimport { AutoTypeStep } from \"./autoType\";\nimport { AutoClickStep } from \"./autoClick\";\nimport { SleepStep } from \"./sleep\";\nimport { ExtractMethods } from \"@/lib/typeUtils\";\nimport { StepActionsFacade } from \"../../tourPlayback/facades\";\nimport { RedirectStep } from \"./redirect\";\nimport { FlowFlexibility } from \"@common/schemas\";\n\nexport type Step =\n | FillerStep\n | UserClickStep\n | DragStep\n | HighlightStep\n | QuestionStep\n | ShowContentStep\n | ModalStep\n | WaitForElementStep\n | AutoTypeStep\n | AutoClickStep\n | SleepStep\n | RedirectStep;\n\nexport type StepActions = ExtractMethods;\n\nexport interface StepFactoryParams {\n actions: StepActions;\n flowFlexibility: FlowFlexibility;\n}\n\nexport class StepFactory {\n static create({ step, actions, flowFlexibility }: { index: number; step: schemas.Step } & StepFactoryParams): Step {\n switch (step.attributes.type) {\n case \"filler\":\n return new FillerStep(step, actions, flowFlexibility);\n case \"userClick\":\n return new UserClickStep(step, actions, flowFlexibility);\n case \"drag\":\n return new DragStep(step, actions, flowFlexibility);\n case \"highlight\":\n return new HighlightStep(step, actions, flowFlexibility);\n case \"question\":\n return QuestionFactory.create(step as schemas.QuestionStep, actions, flowFlexibility);\n case \"redirect\":\n return new RedirectStep(step, actions, flowFlexibility);\n case \"modal\":\n return ModalFactory.create(step as schemas.ModalStep, actions, flowFlexibility);\n case \"showContent\":\n return new ShowContentStep(step, actions, flowFlexibility);\n case \"waitForElement\":\n return new WaitForElementStep(step, actions, flowFlexibility);\n case \"autoType\":\n return new AutoTypeStep(step, actions, flowFlexibility);\n case \"autoClick\":\n return new AutoClickStep(step, actions, flowFlexibility);\n case \"sleep\":\n return new SleepStep(step, actions, flowFlexibility);\n default:\n throw new Error(`Unknown step type: ${(step as schemas.Step).attributes.type}`);\n }\n }\n\n static createList({ steps, actions, flowFlexibility }: { steps: schemas.Step[] } & StepFactoryParams): Step[] {\n if (!steps) {\n return [];\n }\n\n return steps.map((step, index) =>\n StepFactory.create({\n step,\n index,\n actions,\n flowFlexibility,\n })\n );\n }\n}\n","import { FlowHookActions } from \"./hook\";\n\nexport class FinishTourHook {\n actions: FlowHookActions;\n\n constructor(actions: FlowHookActions) {\n this.actions = actions;\n }\n\n execute() {\n this.actions.finishTour();\n }\n}\n","import { FlowHookActions } from \"./hook\";\n\nexport class LoadCheckpointHook {\n actions: FlowHookActions;\n\n constructor(actions: FlowHookActions) {\n this.actions = actions;\n }\n\n execute() {\n this.actions.loadLastCheckpoint();\n }\n}\n","import { ExtractMethods } from \"@/lib/typeUtils\";\nimport { FlowHookType } from \"../tourPlayback/flow\";\nimport { FinishTourHook } from \"./finishTour\";\nimport { LoadCheckpointHook } from \"./loadCheckpoint\";\nimport { FlowHookActionsFacade } from \"../tourPlayback/facades\";\n\nexport type FlowHook = FinishTourHook | LoadCheckpointHook;\n\nexport type FlowHookActions = ExtractMethods;\n\nexport class FlowHookFactory {\n static create(flowHookType: FlowHookType | undefined, actions: FlowHookActions) {\n if (!flowHookType) {\n return undefined;\n }\n\n switch (flowHookType) {\n case \"finishTour\":\n return new FinishTourHook(actions);\n case \"loadCheckpoint\":\n return new LoadCheckpointHook(actions);\n default:\n throw new Error(`Unknown flow hook type: ${flowHookType}`);\n }\n }\n}\n","import * as schemas from \"@common/schemas\";\nimport * as schemasv2 from \"@common/schemas/v2\";\nimport { Step, StepActions, StepFactory } from \"../steps/v2/step\";\nimport { createFlows, CreateSystemFlowsParams, FlowHooks, FlowKey, FlowOptions } from \"./flow\";\nimport { FlowHookActions, FlowHookFactory } from \"../hooks/hook\";\nimport { Flow, Section } from \"./types\";\n\nexport interface BuildAllFlowsParams {\n tourPlayback: schemas.TourPlayback;\n stepActions: StepActions;\n flowHookActions: FlowHookActions;\n systemFlowParams: CreateSystemFlowsParams;\n flowFlexibility: schemas.FlowFlexibility;\n}\n\nexport const buildAllFlows = ({\n tourPlayback,\n stepActions,\n flowHookActions,\n systemFlowParams,\n flowFlexibility,\n}: BuildAllFlowsParams): Record => {\n const flows = createFlows(tourPlayback, systemFlowParams);\n\n return Object.fromEntries(\n Object.entries(flows).map(([key, value]) => [\n key,\n buildFlow({\n key: key as FlowKey,\n sections: value.sections,\n stepActions,\n flowHookActions,\n options: value.options,\n systemFlowParams,\n hooks: value.hooks,\n flowFlexibility,\n }),\n ])\n ) as Record;\n};\n\nexport interface BuildFlowParams {\n key: FlowKey;\n sections: schemasv2.Section[];\n stepActions: StepActions;\n flowHookActions: FlowHookActions;\n systemFlowParams: CreateSystemFlowsParams;\n options: FlowOptions;\n hooks?: FlowHooks;\n flowFlexibility: schemas.FlowFlexibility;\n}\n\nconst buildFlow = ({\n key,\n sections,\n stepActions,\n flowHookActions,\n options,\n hooks,\n flowFlexibility,\n}: BuildFlowParams): Flow => {\n const buildHooks = (hooks?: FlowHooks) => {\n if (!hooks) {\n return undefined;\n }\n\n return {\n onFinish: FlowHookFactory.create(hooks.onFinish, flowHookActions),\n };\n };\n\n return {\n key,\n options,\n hooks: buildHooks(hooks),\n sections: buildSections(sections, stepActions, flowFlexibility),\n };\n};\n\nexport const buildSections = (\n sections: schemasv2.Section[],\n stepActions: StepActions,\n flowFlexibility: schemas.FlowFlexibility\n): Section[] => {\n return sections.map((section, index) => {\n return buildSection(section, stepActions, flowFlexibility, index);\n });\n};\n\nexport const buildSection = (\n section: schemasv2.Section,\n stepActions: StepActions,\n flowFlexibility: schemas.FlowFlexibility,\n index: number = 0\n): Section => {\n return { ...section, steps: buildSteps(section, stepActions, flowFlexibility), index };\n};\n\nexport const buildSteps = (\n section: schemasv2.Section,\n stepActions: StepActions,\n flowFlexibility: schemas.FlowFlexibility\n): Step[] => {\n return StepFactory.createList({ steps: section.steps, actions: stepActions, flowFlexibility });\n};\n","import { createInMemoryStorageHandler, StorageHandler } from \"@/lib/storage\";\nimport { makeAutoObservable } from \"mobx\";\n\nexport interface UserState {\n dismissedTourGuideIds?: string[];\n finishedTourGuideIds?: string[];\n updatedAt?: number;\n isHydrated?: boolean;\n}\n\nexport class UserStateStorage {\n private isPreview: boolean;\n private storage: StorageHandler;\n private _state: UserState;\n\n constructor(isPreview: boolean, storage: StorageHandler) {\n this.isPreview = isPreview;\n this.storage = storage;\n this._state = this.get();\n makeAutoObservable(this);\n }\n\n private storageKey(): string {\n return `pyne-user-state${this.isPreview ? \"preview\" : \"\"}`;\n }\n\n get dismissedTourGuideIds(): string[] {\n return this._state.dismissedTourGuideIds || [];\n }\n\n get finishedTourGuideIds(): string[] {\n return this._state.finishedTourGuideIds || [];\n }\n\n get isHydrated(): boolean {\n return this._state.isHydrated || false;\n }\n\n public isExists(): boolean {\n return this.storage.isKeyExists(this.storageKey());\n }\n\n public get(): UserState {\n return this.storage.get(this.storageKey(), {});\n }\n\n public clear(): void {\n this.storage.remove(this.storageKey());\n this._state = {};\n }\n\n public set(state: Partial): void {\n this._state = { ...this._state, ...state, updatedAt: Date.now() };\n this.storage.set(this.storageKey(), this._state);\n }\n\n public addFinishedGuide(guideId: string): void {\n const finishedTourGuideIds = this._state.finishedTourGuideIds || [];\n this.set({ finishedTourGuideIds: [...finishedTourGuideIds, guideId] });\n }\n\n public addDismissedGuide(guideId: string): void {\n const dismissedTourGuideIds = this._state.dismissedTourGuideIds || [];\n this.set({ dismissedTourGuideIds: [...dismissedTourGuideIds, guideId] });\n }\n\n public hydrate(state: Partial): void {\n const currentState = this._state;\n\n if (Object.keys(state).length === 0) {\n const hydratedState = { ...currentState, isHydrated: true };\n this._state = hydratedState;\n this.storage.set(this.storageKey(), hydratedState);\n return;\n }\n\n const isUserStateStale = state.updatedAt && currentState.updatedAt && state.updatedAt > currentState.updatedAt;\n if (isUserStateStale) {\n return;\n }\n\n const hydratedState = { ...state, isHydrated: true };\n this._state = hydratedState;\n this.storage.set(this.storageKey(), hydratedState);\n }\n}\n\nexport const buildInMemoryUserStateStorage = () => new UserStateStorage(false, createInMemoryStorageHandler());\n","import { EmptyPayload } from \"@/lib/events/types\";\n\nexport type TourFinishManagerEvents = {\n finished: EmptyPayload;\n};\n\nexport const TourFinishManagerNamespace = \"tourFinishManager\" as const;\n","import { makeAutoObservable } from \"mobx\";\nimport { Step } from \"../steps/v2/step\";\nimport { ModalChoice, QuestionChoice } from \"@common/models\";\nimport { EventEmitter } from \"@/lib/events/eventEmitter\";\nimport { TourFinishManagerEvents, TourFinishManagerNamespace } from \"./tourFinishManager.events\";\n\nexport class TourFinishManager {\n currentStep?: Step;\n stopListenStepEvents?: () => void;\n events = new EventEmitter(\n TourFinishManagerNamespace\n );\n\n constructor() {\n makeAutoObservable(this);\n }\n\n setCurrentStep(step: Step, isLastStep: boolean) {\n if (this.currentStep?.id === step.id) return;\n\n this.clearCurrentStep();\n this.currentStep = step;\n\n this.stopListenStepEvents = step.events.on(\"*\", (event, { payload }) => {\n const isChoiceTypeIn = (choiceTypes: (QuestionChoice | ModalChoice)[\"type\"][]) => {\n return choiceTypes.includes((payload as { choice: QuestionChoice | ModalChoice }).choice.type);\n };\n\n const isQuestionAnswered = step.attributes.type === \"question\" && event === \"questionAnswered\";\n const isModalAnswered = step.attributes.type === \"modal\" && event === \"modalAnswered\";\n const isQuestionOrModalAnswered = isQuestionAnswered || isModalAnswered;\n const isFinishTourChoiceSelected = isQuestionOrModalAnswered && isChoiceTypeIn([\"finishTour\"]);\n\n if (!isLastStep && !isFinishTourChoiceSelected) {\n return;\n }\n\n if (isQuestionOrModalAnswered && !isChoiceTypeIn([\"suspendTour\"])) {\n this.events.emit(\"finished\", {});\n return;\n }\n\n if (!step.isBlockingStepType && event === \"initialized\") {\n this.events.emit(\"finished\", {});\n return;\n }\n\n const isBlockingStepTypeExcludingModalAndQuestion =\n step.isBlockingStepType && ![\"modal\", \"question\"].includes(step.attributes.type);\n\n if (isBlockingStepTypeExcludingModalAndQuestion && event === \"disposed\") {\n this.events.emit(\"finished\", {});\n return;\n }\n });\n }\n\n clearCurrentStep() {\n this.stopListenStepEvents?.();\n this.currentStep = undefined;\n }\n\n stop() {\n this.stopListenStepEvents?.();\n }\n}\n","import { EmptyPayload } from \"@/lib/events/types\";\n\nexport type TourEngagedManagerEvents = {\n engaged: EmptyPayload;\n};\n\nexport const TourEngagedManagerNamespace = \"tourEngagedManager\" as const;\n","import { makeAutoObservable } from \"mobx\";\nimport { Step } from \"../steps/v2/step\";\nimport { EventEmitter } from \"@/lib/events/eventEmitter\";\nimport { TourPlayback } from \"@common/schemas/v2/tour\";\nimport { TourEngagedManagerEvents, TourEngagedManagerNamespace } from \"./tourEngagedManager.events\";\nimport { QuestionChoice, ModalChoice } from \"@common/models\";\n\nexport class TourEngagedManager {\n private currentStep?: Step;\n private stopListenStepEvents?: () => void;\n private tourPlayback: TourPlayback;\n private hasEmittedEngaged = false;\n\n events = new EventEmitter(\n TourEngagedManagerNamespace\n );\n\n constructor(tourPlayback: TourPlayback) {\n this.tourPlayback = tourPlayback;\n\n makeAutoObservable(this);\n }\n\n setCurrentStep(step: Step) {\n if (this.currentStep?.id === step.id) return;\n\n this.clearCurrentStep();\n this.currentStep = step;\n this.checkEngagement();\n }\n\n private checkEngagement() {\n if (this.hasEmittedEngaged) return;\n\n const steps = this.tourPlayback.sections.flatMap((section) => section.steps);\n const currentStepIndex = steps.findIndex((s) => s.id === this.currentStep?.id);\n\n if (currentStepIndex === -1) return;\n\n // Count non-redirect steps up to current step\n const nonRedirectStepsCount = steps\n .slice(0, currentStepIndex + 1)\n .filter((step) => step.attributes.type !== \"redirect\").length;\n\n if (nonRedirectStepsCount >= 2) {\n this.hasEmittedEngaged = true;\n this.events.emit(\"engaged\", {});\n }\n }\n\n clearCurrentStep() {\n this.stopListenStepEvents?.();\n this.currentStep = undefined;\n }\n\n stop() {\n this.stopListenStepEvents?.();\n this.hasEmittedEngaged = false;\n }\n}\n","import { GuideSettings } from \"@common/models\";\nimport type { FlowFlexibility, PyneSettings, TourPlayback } from \"@common/schemas\";\nimport { debounce, merge, pickBy } from \"lodash-es\";\nimport { autorun, makeAutoObservable, runInAction, toJS } from \"mobx\";\nimport { debugLog, log } from \"../../log\";\nimport { getUrl, navigateTo, reloadWindow } from \"../../window\";\nimport { AvatarManager, SectionMediaUrls } from \"./avatarManager\";\nimport { FlowHookActionsFacade, StepActionsFacade } from \"./facades\";\nimport { CreateSystemFlowsParams, FlowKey, systemFlowTypes } from \"./flow\";\nimport { MultipleChoiceModalStep } from \"../steps/v2/modal\";\nimport { MultipleChoiceQuestionStep } from \"../steps/v2/question\";\nimport { Step } from \"../steps/v2/step\";\nimport { AvatarStateStorage, buildInMemoryAvatarStateStorage } from \"../persistent-storage/avatarState\";\nimport { TourStateStorage, buildInMemoryTourStateStorage } from \"../persistent-storage/tourState\";\nimport { TourStartStrategy } from \"../tourStartManager\";\nimport { TourTrackManager } from \"../tourTrackManager\";\nimport { fromStream } from \"mobx-utils\";\nimport { createFlowStateActor, createFlowStateStream } from \"./flowStateMachine\";\nimport {\n TourPlaybackEventContext,\n TourPlaybackManagerEvents,\n TourPlaybackNamespace,\n} from \"./tourPlaybackManager.events\";\nimport { Checkpoint, Flow, FlowPosition, FlowState, Section, SuspendReason } from \"./types\";\nimport { buildAllFlows } from \"./build\";\nimport { globalEventBus } from \"@/lib/events/eventBus\";\nimport { EventEmitter } from \"@/lib/events/eventEmitter\";\nimport { buildInMemoryUserStateStorage, UserStateStorage } from \"../persistent-storage/userState\";\nimport { waitForOnTrackConditions } from \"../onTrackConditionCheck\";\nimport { pageInfo } from \"@/stores/PageInfo\";\nimport { TourFinishManager } from \"./tourFinishManager\";\nimport { TourEngagedManager } from \"./tourEngagedManager\";\nimport { store } from \"@/store\";\n\nexport interface TourPlaybackManagerParams {\n pyneSettings: PyneSettings;\n guideId: string;\n sessionId: string;\n startedAt: number;\n tourPlayback: TourPlayback;\n settings: GuideSettings;\n tourStateStorage?: TourStateStorage;\n userStateStorage?: UserStateStorage;\n avatarStateStorage?: AvatarStateStorage;\n startFromStepId?: string;\n shouldAutoPlayFirstStep?: boolean;\n skipBlobMediaPreload?: boolean;\n startStrategy?: TourStartStrategy;\n mediaPlaybackRate?: number;\n tabId: string;\n}\n\nexport type SubtitleText = {\n word: string;\n isSpoken: boolean;\n};\n\nexport class TourPlaybackManager {\n pyneSettings: PyneSettings;\n guideId: string;\n tourPlayback: TourPlayback;\n flows: Record;\n avatarManager: AvatarManager;\n settings: GuideSettings;\n private pageInfo = pageInfo;\n tourStateStorage: TourStateStorage;\n userStateStorage: UserStateStorage;\n tourTrackManager: TourTrackManager;\n startFromStepId?: string;\n startStrategy: TourStartStrategy;\n tourFinishManager: TourFinishManager;\n tourEngagedManager: TourEngagedManager;\n flowFlexibility: FlowFlexibility;\n shouldAutoPlayFirstStep?: boolean;\n events = new EventEmitter(\n TourPlaybackNamespace\n );\n tabId: string;\n startedAt: number;\n sessionId: string;\n\n status: \"initialized\" | \"started\" | \"suspended\" | \"finished\" | \"dismissed\" | \"terminated\" = \"initialized\";\n\n _currentTargetElement?: Element | null;\n currentFlowKey?: FlowKey;\n currentFlow?: Flow;\n currentTime: number = 0;\n\n readonly initialFlowState: FlowState = {\n currentTime: 0,\n currentSectionIndex: 0,\n currentStepIndex: 0,\n };\n\n readonly defaultStartStrategy: TourStartStrategy = { type: \"startOver\" };\n\n flowStateStack: FlowState[] = [];\n checkpoints: Checkpoint[] = [];\n\n isWaitingForIntro = false;\n\n flowStateActor?: ReturnType;\n flowStateStream?: ReturnType;\n\n stopGlobalEventBusMiddleware?: () => void;\n stopListeningPageUrlChange?: () => void;\n\n constructor(params: TourPlaybackManagerParams) {\n makeAutoObservable(this);\n\n this.pyneSettings = params.pyneSettings;\n this.guideId = params.guideId;\n this.tourPlayback = params.tourPlayback;\n this.startStrategy = params.startStrategy ?? this.defaultStartStrategy;\n this.settings = params.settings;\n this.tourStateStorage = params.tourStateStorage ?? buildInMemoryTourStateStorage();\n this.userStateStorage = params.userStateStorage ?? buildInMemoryUserStateStorage();\n this.tourTrackManager = new TourTrackManager();\n this.tourFinishManager = new TourFinishManager();\n this.flowFlexibility = this.settings.flow_flexibility;\n this.flows = this.buildFlows();\n this.isWaitingForIntro = this.getWaitingForIntro();\n this.tabId = params.tabId;\n this.tourEngagedManager = new TourEngagedManager(this.tourPlayback);\n\n this.sessionId = params.sessionId;\n this.startedAt = params.startedAt;\n const sectionMedias = this.tourPlayback.sections.map((section) => {\n return { sectionId: section.id, mediaUrl: section.avatarMediaUrl, mediaDuration: section.mediaDuration };\n });\n\n const systemFlows = pickBy(this.flows, (flow) => systemFlowTypes.includes(flow.key as any));\n\n const systemFlowMedias = Object.entries(systemFlows).reduce((acc, [key, value]) => {\n value.sections.forEach((section) => {\n if (section.avatarMediaUrl) {\n acc[section.id] = section.avatarMediaUrl;\n }\n });\n return acc;\n }, {} as SectionMediaUrls);\n\n this.avatarManager = new AvatarManager({\n sectionMedias: sectionMedias,\n sytemFlowMediaUrls: systemFlowMedias,\n stateStorage: params.avatarStateStorage ?? buildInMemoryAvatarStateStorage(),\n skipBlobMediaPreload: params.skipBlobMediaPreload,\n playbackRate: params.mediaPlaybackRate,\n mediaAmplificationRate: params.pyneSettings.mediaAmplificationRate,\n highlightPlayButtonEnabled: params.pyneSettings.highlightPlayButton,\n showWatermark: params.pyneSettings.showWatermark,\n });\n\n this.checkpoints = this.tourStateStorage.listCheckpoints();\n\n autorun(() => {\n this.tourStateStorage.setCheckpoints(this.checkpoints);\n });\n\n this.stopListeningPageUrlChange = this.pageInfo.events.on(\"urlChanged\", ({ payload: { url } }) => {\n this.tourStateStorage.set({ lastPageUrl: url });\n });\n\n this.startFromStepId = params.startFromStepId;\n this.shouldAutoPlayFirstStep = params.shouldAutoPlayFirstStep;\n this.validate();\n\n this.registerGlobalEventBusMiddleware();\n this.subscribeToAvatarManagerEvents();\n this.subscribeToTourTrackManagerEvents();\n this.subscribeToTourFinishManagerEvents();\n this.subscribeToTourEngagedManagerEvents();\n }\n\n private setupFlowStateMachine(flow: Flow, initialFlowState: FlowState) {\n this.flowStateActor?.stop();\n this.flowStateStream?.dispose();\n\n this.flowStateActor = createFlowStateActor({\n input: { flow: flow, initialFlowState: initialFlowState, flowFlexibility: this.flowFlexibility },\n hooks: {\n onSectionTransition: this.handleSectionTransition.bind(this),\n onStepTransition: this.handleStepTransition.bind(this),\n onWaitBlockingStep: this.handleWaitBlockingStep.bind(this),\n onFlowFinish: this.handleFlowFinish.bind(this),\n onStepDispose: this.handleStepDispose.bind(this),\n onStepRun: this.handleStepRun.bind(this),\n },\n });\n this.flowStateStream = fromStream(this.flowStateActor);\n this.flowStateActor?.start();\n const cancel = autorun(() => {\n if (this.avatarManager.isPlaying) {\n this.flowStateActor?.send({ type: \"mediaPlaying\" });\n cancel();\n }\n });\n }\n\n private handleWaitBlockingStep(_pos: FlowPosition, step: Step) {\n this.pauseMediaIfStepIsBlocking(step);\n }\n\n private handleStepTransition(pos: FlowPosition, step: Step) {\n this.tourFinishManager.setCurrentStep(step, this.isLastStepInTourFlow(step));\n this.tourEngagedManager.setCurrentStep(step);\n this.tourTrackManager.setCurrentStep(step);\n this.avatarManager.setCurrentStep(step);\n this.updateTourStateStep(step);\n this.events.emit(\"stepTransitioned\", { step }, this.buildEventContext(pos));\n }\n\n private handleStepRun(pos: FlowPosition, _step: Step) {\n this.events.emit(\"stepExecuted\", {}, this.buildEventContext(pos));\n }\n\n private handleStepDispose(_pos: FlowPosition, step: Step) {\n this.setLastCompletedTourStep(step.id);\n this.tourTrackManager.clearCurrentStep();\n this.tourFinishManager.clearCurrentStep();\n this.tourEngagedManager.clearCurrentStep();\n }\n\n private handleSectionTransition(_pos: FlowPosition, section: Section) {\n this.avatarManager.setCurrentSection(section, section.steps[0], {\n isProgressRingVisible: this.currentFlow?.options.isAvatarProgressRingVisible ?? true,\n autoPlay: true,\n currentTime: 0,\n });\n }\n\n private handleFlowFinish() {\n this.finishFlow();\n }\n\n private getWaitingForIntro() {\n const hasWatched = this.tourStateStorage.getHasWatchedIntro();\n\n if (hasWatched === undefined) {\n return this.settings.opener_type !== \"none\" && !!this.settings.opener_settings?.title;\n }\n\n return false;\n }\n\n validate() {\n if (this.tourPlayback.sections.length === 0) {\n throw new Error(\"No sections found in the tour playback\");\n }\n\n const isOnlyOneSection = this.tourPlayback.sections.length === 1;\n if (isOnlyOneSection && this.tourPlayback.sections[0].steps.length === 0) {\n throw new Error(\"No steps found in the tour playback\");\n }\n }\n\n start() {\n this.initializeTourState();\n\n if (!this.isWaitingForIntro) {\n this.status = \"started\";\n log(\"starting tour\");\n\n if (this.startStrategy.type === \"startSuspended\") {\n this.suspendTour(this.startStrategy.reason, { skipAnalytics: true });\n return;\n }\n\n if (this.startStrategy.type === \"startOver\") {\n this.startFlow(\"tour\", { flowState: this.flowState, autoPlay: this.shouldAutoPlayFirstStep });\n this.events.emit(\"started\", {}, this.buildEventContext());\n return;\n }\n\n if (this.startStrategy.type === \"resume\") {\n const flowState = this.calculateFlowStateFromStepId(this.startStrategy.stepId);\n this.startFlow(\"tour\", { flowState: flowState, autoPlay: this.shouldAutoPlayFirstStep });\n this.events.emit(\"started\", {}, this.buildEventContext());\n return;\n }\n\n if (this.startStrategy.type === \"bringBack\") {\n this.startFlow(\"wanderingOff\");\n this.events.emit(\"started\", {}, this.buildEventContext());\n }\n }\n }\n\n get flowState(): FlowState {\n const machineFlowState = this.flowStateStream?.current?.context;\n return machineFlowState ?? this.initialFlowState;\n }\n\n get flowStatus() {\n return this.flowStateStream?.current?.value;\n }\n\n finishIntro() {\n this.isWaitingForIntro = false;\n this.tourStateStorage.setHasWatchedIntro(true);\n this.start();\n }\n\n startFlow(flowKey: FlowKey, options?: { autoPlay?: boolean; flowState?: FlowState }) {\n if (flowKey !== \"tour\") {\n this.flowStateStack.push(this.flowState);\n }\n\n const defaultOptions = {\n autoPlay: true,\n flowState: this.initialFlowState,\n };\n\n const { autoPlay, flowState } = merge({}, defaultOptions, options);\n\n const flow = this.flows[flowKey];\n this.currentFlow = flow;\n this.currentFlowKey = flowKey;\n\n this.setupFlowStateMachine(flow, flowState);\n\n this.avatarManager.setCurrentSection(this.currentSection!, this.currentStep!, {\n currentTime: flowState.currentTime,\n autoPlay,\n isProgressRingVisible: flow.options.isAvatarProgressRingVisible,\n });\n\n this.status = \"started\";\n this.events.emit(\"flowStarted\", {}, this.buildEventContext());\n log(\"Flow started\", { flowKey, flowState });\n }\n\n jumpToStepId(stepId: string) {\n const flowState = this.calculateFlowStateFromStepId(stepId);\n this.startFlow(\"tour\", { flowState });\n }\n\n private setCurrentTime(time: number) {\n this.currentTime = time;\n this.flowStateActor?.send({ type: \"timeUpdate\", currentTime: time });\n }\n\n private replayStep(step: Step) {\n this.avatarManager.seekMedia(step.start);\n this.flowStateActor?.send({ type: \"replay\" });\n this.playIfNotExceeded();\n }\n\n private playIfNotExceeded() {\n const currentStep = this.currentStep;\n if (!currentStep) return;\n\n if (this.currentTime < currentStep.end) {\n this.avatarManager.play();\n }\n }\n\n private isEndOfStepReached() {\n return this.currentStep && this.currentStep.end <= this.currentTime;\n }\n\n private finishFlow() {\n if (!this.currentFlowKey || !this.currentFlow) return;\n this.events.emit(\"flowFinished\", {}, this.buildEventContext());\n this.currentFlow.hooks?.onFinish?.execute();\n }\n\n dismissTour() {\n this.status = \"dismissed\";\n this.avatarManager.terminate();\n this.events.emit(\"dismissed\", {}, this.buildEventContext());\n }\n\n finishTour() {\n if (this.currentFlowKey !== \"tour\") {\n return;\n }\n this.status = \"finished\";\n this.avatarManager.terminate();\n this.events.emit(\"finished\", {}, this.buildEventContext());\n }\n\n finishCriteriaMet() {\n this.events.emit(\"finishCriteriaMet\", {}, this.buildEventContext());\n }\n\n engagedCriteriaMet() {\n this.events.emit(\"userEngaged\", {}, this.buildEventContext());\n }\n\n terminateTour() {\n this.status = \"terminated\";\n this.clear();\n const eventContext = this.buildEventContext();\n this.avatarManager.terminate();\n this.events.emit(\"terminated\", {}, eventContext);\n }\n\n switchTour(guideId: string) {\n this.status = \"finished\";\n this.events.emit(\"tourSwitched\", { guideId });\n }\n\n pauseTour() {\n this.avatarManager.pause();\n }\n\n pauseMediaIfStepIsBlocking(step: Step) {\n if (step.isBlocking) {\n this.avatarManager.pause();\n }\n }\n\n suspendTour(reason: SuspendReason, options: { skipAnalytics: boolean } = { skipAnalytics: false }) {\n this.status = \"suspended\";\n this.avatarManager.minimize();\n this.tourStateStorage.set({ isSuspended: true, suspendReason: reason });\n this.events.emit(\"suspended\", {}, this.buildEventContext(), { skipGlobal: options.skipAnalytics });\n }\n\n async unsuspendTour() {\n if (await this.isLastCheckpointOnTrack()) {\n this.tourStateStorage.set({ isSuspended: false });\n await this.loadLastCheckpoint();\n this.events.emit(\"unsuspended\", {}, this.buildEventContext());\n return;\n }\n\n this.tourStateStorage.set({ isSuspended: false });\n this.events.emit(\"unsuspended\", {}, this.buildEventContext());\n this.startFlow(\"unsuspend\");\n }\n\n continueTour() {\n this.status = \"started\";\n this.avatarManager.expand();\n this.unsuspendTour();\n }\n\n async loadLastCheckpoint() {\n const lastCheckpoint = this.getLastCheckpoint();\n\n if (!lastCheckpoint) {\n reloadWindow();\n return;\n }\n\n const isLastCheckpointOnTrack = await this.isLastCheckpointOnTrack();\n if (!isLastCheckpointOnTrack) {\n navigateTo(lastCheckpoint.url);\n return;\n }\n\n const tourFlowState = this.getLastCheckpointFlowState();\n this.startFlow(\"tour\", { flowState: tourFlowState, autoPlay: true });\n this.events.emit(\"checkpointLoaded\", {}, this.buildEventContext());\n }\n\n private async isLastCheckpointOnTrack() {\n const lastCheckpoint = this.getLastCheckpoint();\n if (!lastCheckpoint) return false;\n\n const stepId = lastCheckpoint.stepId;\n const step = this.findTourStepById(stepId);\n if (!step) return false;\n\n const currentUrl = getUrl();\n\n const isOnTrack = await waitForOnTrackConditions(step.attributes.onTrackConditions, currentUrl);\n return isOnTrack;\n }\n\n private findTourStepById(stepId: string) {\n return this.tourSteps.find((step) => step.id === stepId);\n }\n\n private getLastCheckpointFlowState() {\n const lastCheckpoint = this.getLastCheckpoint();\n if (!lastCheckpoint) return this.initialFlowState;\n return this.calculateFlowStateFromStepId(lastCheckpoint.stepId);\n }\n\n private getLastCheckpoint() {\n return this.checkpoints[this.checkpoints.length - 1];\n }\n\n private calculateFlowStateFromStepId(stepId: string) {\n const sectionIndex = this.flows.tour.sections.findIndex((section) =>\n section.steps.some((step) => step.id === stepId)\n );\n const stepIndex = this.flows.tour.sections[sectionIndex].steps.findIndex((step) => step.id === stepId);\n const stepStartTime = this.flows.tour.sections[sectionIndex].steps[stepIndex].start;\n const flowState = {\n currentTime: stepStartTime,\n currentSectionIndex: sectionIndex,\n currentStepIndex: stepIndex,\n };\n return flowState;\n }\n\n setCurrentTargetElement(el?: Element | null) {\n const nextTarget = el;\n\n this.runOnTargetElementHighlighted(nextTarget, () => {\n this.events.emit(\"targetElementHighlighted\", {}, this.buildEventContext());\n });\n\n runInAction(() => {\n this._currentTargetElement = nextTarget;\n });\n\n if (this._currentTargetElement) {\n this._currentTargetElement.scrollIntoView({ behavior: \"smooth\", block: \"center\", inline: \"center\" });\n }\n }\n\n getTargetElement(stepId: string) {\n return this.tourTrackManager.getTargetElement(stepId);\n }\n\n onTargetElementNotFound() {\n this.startFlow(\"targetNotFound\");\n }\n\n onUserWanderedOff() {\n this.events.emit(\"userWanderedOff\", {}, this.buildEventContext());\n this.startFlow(\"wanderingOff\");\n }\n\n runOnTargetElementHighlighted = debounce(\n (target?: Element | null, callback?: () => void) => {\n if (target) {\n callback?.();\n }\n },\n 500,\n { leading: false, trailing: true }\n );\n\n onQuestionChoiceSelected(choiceId: string) {\n if (!this.currentStep) return;\n if (this.currentStep instanceof MultipleChoiceQuestionStep) {\n const choiceType = this.currentStep.attributes.choices.find((c) => c.id === choiceId)?.type ?? \"unknown\";\n this.events.emit(\"questionChoiceSelected\", { choiceId, choiceType }, this.buildEventContext());\n this.currentStep.answer(choiceId);\n }\n }\n\n onModalChoiceSeleceted(choiceId: string) {\n if (!this.currentStep) return;\n if (this.currentStep instanceof MultipleChoiceModalStep) {\n this.currentStep.answer(choiceId);\n }\n }\n\n onMediaFinish() {\n this.flowStateActor?.send({ type: \"mediaFinished\" });\n }\n\n skipCurrentStep() {\n if (!this.currentStep) return;\n this.skipStep(this.currentStep);\n }\n\n skipStep(step: Step) {\n if (this.isLastStepInSection(step)) {\n this.avatarManager.seekMediaToEnd();\n this.avatarManager.play();\n return;\n }\n\n const nextStep = this.findNextStepInSection(step);\n if (!nextStep) return;\n\n this.avatarManager.seekMedia(nextStep.start);\n this.avatarManager.play();\n }\n\n findNextStepInSection(step: Step) {\n const currentSection = this.currentSection;\n if (!currentSection) return null;\n\n const stepIndex = currentSection.steps.findIndex((s) => s.id === step.id);\n if (stepIndex === -1) return null;\n if (stepIndex === currentSection.steps.length - 1) return null;\n\n return currentSection.steps[stepIndex + 1];\n }\n\n isLastStepInSection(step: Step) {\n const currentSection = this.currentSection;\n if (!currentSection) return false;\n\n const stepIndex = currentSection.steps.findIndex((s) => s.id === step.id);\n if (stepIndex === -1) return false;\n\n return stepIndex === currentSection.steps.length - 1;\n }\n\n get prompt() {\n if (!this.currentStep) return null;\n if (this.isPlayingHeadingGap) return null;\n if (this.status === \"terminated\") return null;\n if (this.status === \"suspended\") return null;\n\n return this.currentStep.prompt;\n }\n\n get modalContent() {\n if (!this.currentStep) return null;\n if (this.isPlayingHeadingGap) return null;\n if (this.status === \"terminated\") return null;\n if (this.status === \"suspended\") return null;\n\n if (!(this.currentStep instanceof MultipleChoiceModalStep)) {\n return null;\n }\n return this.currentStep.modal;\n }\n\n get currentTargetElement() {\n if (!this.currentStep) return null;\n if (this.isPlayingHeadingGap) return null;\n if (this.status === \"terminated\") return null;\n if (this.status === \"suspended\") return null;\n\n return this._currentTargetElement;\n }\n\n get additionalContent() {\n if (!this.currentStep) return null;\n if (this.isPlayingGap) return null;\n if (this.status === \"terminated\") return null;\n if (this.status === \"suspended\") return null;\n\n return this.currentStep?.additionalContent;\n }\n\n get subtitles() {\n if (!this.currentStep) return null;\n if (this.status === \"terminated\") return null;\n if (this.status === \"suspended\") return null;\n if (!this.avatarManager.isCaptionsVisible) return null;\n if (this.currentFlowKey !== \"tour\") return null;\n\n return this.getSubtitlesForCurrentTime();\n }\n\n get finishedTourGuideIds() {\n return this.userStateStorage.finishedTourGuideIds;\n }\n\n get cursorSettings() {\n if (!this.currentStep?.attributes.isHighlightable() || !this.currentTargetElement) {\n return {\n visible: false,\n click: undefined,\n };\n }\n\n const click = this.currentStep.attributes.virtualCursor.animationType;\n const visible =\n this.currentStep.attributes.virtualCursor.animationType !== \"hidden\" && !!this._currentTargetElement;\n\n return {\n visible,\n click,\n };\n }\n\n get isInitializing() {\n return this.avatarManager.isInitializing;\n }\n\n get isPlayingGap() {\n if (!this.currentStep) return true;\n return this.isPlayingHeadingGap || this.isPlayingTrailingGap;\n }\n\n get isPlayingHeadingGap() {\n if (!this.currentStep) return true;\n return this.currentTime < this.currentStep?.start;\n }\n\n get isPlayingTrailingGap() {\n if (!this.currentStep) return true;\n return this.currentTime > this.currentStep?.end;\n }\n\n get currentSection(): Section | undefined {\n return this.currentFlow?.sections[this.flowState.currentSectionIndex];\n }\n\n get currentStep(): Step | undefined {\n return this.currentSection?.steps[this.flowState.currentStepIndex];\n }\n\n get tourFlow() {\n return this.flows.tour;\n }\n\n private saveCheckpoint(step: Step, url: string) {\n const checkpoint: Checkpoint = { stepId: step.id, stepType: step.attributes.type, url, createdAt: Date.now() };\n this.checkpoints.push(checkpoint);\n this.events.emit(\"checkpointSaved\", { checkpoint }, this.buildEventContext());\n }\n\n handleProceedNextFromStep() {\n // Temp fix, until we have a better way to handle this\n this.tourTrackManager.stopWatch?.();\n this.seekMediaToEndOfStepIfNotReached();\n this.avatarManager.play();\n }\n\n private setLastCompletedTourStep(stepId: string) {\n if (this.currentFlowKey !== \"tour\") return;\n\n this.tourStateStorage.setLastCompletedStepId(stepId);\n }\n\n private seekMediaToEndOfStepIfNotReached() {\n if (!this.currentStep) return;\n if (!this.isEndOfStepReached()) {\n this.avatarManager.seekMedia(this.currentStep.end);\n }\n }\n\n private buildFlows() {\n const systemFlowParams: CreateSystemFlowsParams = {\n unsuspendFlow: {\n resumeTour: this.settings.fillers.resumeTour!,\n },\n targetNotFoundFlow: {\n targetNotFound: this.settings.fillers.targetNotFound!,\n },\n wanderingOffFlow: {\n targetLost: this.settings.fillers.targetLost!,\n resumeTour: this.settings.fillers.resumeTour!,\n },\n };\n\n return buildAllFlows({\n tourPlayback: this.tourPlayback,\n stepActions: new StepActionsFacade(this),\n flowHookActions: new FlowHookActionsFacade(this),\n flowFlexibility: this.flowFlexibility,\n systemFlowParams,\n });\n }\n\n private getSubtitlesForCurrentTime(): SubtitleText[][] {\n if (!this.currentSection) return [];\n\n const transcript = this.currentSection.transcript;\n const subTranscripts = this.divideSubtitles(transcript);\n const currentChunkIndex = subTranscripts.findIndex((subTranscript) => {\n const endTime = subTranscript[subTranscript.length - 1][0];\n return this.currentTime <= endTime;\n });\n\n if (currentChunkIndex === -1) {\n return [];\n }\n\n const currentSubTranscript = subTranscripts[currentChunkIndex];\n const words: SubtitleText[] = currentSubTranscript.map(([time, word]) => ({\n word,\n isSpoken: time <= this.currentTime,\n }));\n\n let charsRead = 0;\n const firstCutoff = words.findIndex(({ word }) => {\n if (charsRead <= 40) {\n charsRead += word.length + 1;\n } else {\n return true;\n }\n });\n const firstLine = words.slice(0, firstCutoff);\n\n charsRead = 0;\n const secondCutoff = words\n .filter((_, index) => firstCutoff < index)\n .findIndex(({ word }) => {\n if (charsRead <= 35) {\n charsRead += word.length + 1;\n } else {\n return true;\n }\n });\n const secondLine = words.slice(firstCutoff, secondCutoff === -1 ? words.length : secondCutoff);\n const lines = [firstLine, secondLine];\n\n return lines;\n }\n\n private updateTourStateStep(step: Step) {\n if (this.currentFlowKey !== \"tour\") return;\n\n this.tourStateStorage.set({\n tabId: this.tabId,\n activeStepId: step.id,\n lastStepTransitionTimestamp: Date.now(),\n });\n }\n\n private initializeTourState() {\n this.tourStateStorage.set({\n activeTourGuideId: this.guideId,\n expirationTimeoutMinutes: this.settings.tour_expiration_timeout,\n tourPlaybackVersion: this.tourPlayback.version,\n lastPageUrl: this.pageInfo.url,\n tabId: this.tabId,\n });\n }\n\n private divideSubtitles(arr: [number, string][]): [number, string][][] {\n return arr\n .filter(([, str]) => str.trim())\n .reduce((dividedSlices: [number, string][][], [time, text]) => {\n if (\n !dividedSlices.length ||\n dividedSlices[dividedSlices.length - 1].reduce((acc, [, str]) => acc + str.length + 1, 0) + text.length > 75\n ) {\n dividedSlices.push([[time, text]]);\n } else {\n dividedSlices[dividedSlices.length - 1].push([time, text]);\n }\n return dividedSlices;\n }, []);\n }\n\n private subscribeToAvatarManagerEvents() {\n this.avatarManager.events.on(\"mediaTimeUpdated\", ({ payload: time }) => {\n this.setCurrentTime(time);\n });\n this.avatarManager.events.on(\"mediaFinished\", this.onMediaFinish.bind(this));\n this.avatarManager.events.on(\"stepReplayed\", ({ payload: step }) => {\n this.replayStep(step);\n });\n this.avatarManager.events.on(\"stepSkipped\", ({ payload: step }) => {\n this.skipStep(step);\n });\n this.avatarManager.events.on(\"minimizeClicked\", () => {\n this.suspendTour(\"userAction\");\n });\n this.avatarManager.events.on(\"expandClicked\", () => {\n this.continueTour();\n });\n this.avatarManager.events.on(\"dismissClicked\", () => {\n this.dismissTour();\n });\n }\n\n private subscribeToTourTrackManagerEvents() {\n this.tourTrackManager.events.on(\"wanderedOff\", ({ payload: step }) => {\n if (this.shouldTriggerFallback(step)) {\n this.onUserWanderedOff();\n }\n });\n\n this.tourTrackManager.events.on(\"targetNotFound\", ({ payload: step }) => {\n this.events.emit(\"targetElementNotFound\", {}, this.buildEventContext());\n if (this.shouldTriggerFallback(step)) {\n this.onTargetElementNotFound();\n }\n });\n\n this.tourTrackManager.events.on(\"trackSatisfied\", ({ payload: step }) => {\n if (step.attributes.isCheckpoint) {\n this.saveCheckpoint(step, getUrl());\n }\n });\n }\n\n isStepOnTrack(stepId: string) {\n return this.tourTrackManager.isOnTrack(stepId);\n }\n\n private shouldTriggerFallback(step: Step) {\n return (\n this.flowFlexibility === \"strict\" || (this.flowFlexibility === \"flexible\" && step.isBlockingAndTargetableStepType)\n );\n }\n\n private subscribeToTourFinishManagerEvents() {\n this.tourFinishManager.events.on(\"finished\", () => {\n this.finishCriteriaMet();\n });\n }\n\n private subscribeToTourEngagedManagerEvents() {\n this.tourEngagedManager.events.on(\"engaged\", () => {\n this.engagedCriteriaMet();\n });\n }\n\n private registerGlobalEventBusMiddleware() {\n this.stopGlobalEventBusMiddleware = globalEventBus.use(\"*\", (context, type) => {\n if (type.startsWith(TourPlaybackNamespace)) {\n return context;\n }\n\n return { ...this.buildEventContext(), ...context };\n });\n }\n\n get isSuspended() {\n return this.status === \"suspended\";\n }\n\n get isAudioAvatar() {\n return this.tourPlayback?.mediaType === \"audio\";\n }\n\n get tourSteps() {\n return this.tourFlow.sections.flatMap((section) => section.steps);\n }\n\n get showSubtitles() {\n if (!this.subtitles) return false;\n return this.subtitles.length > 0 && !!this.avatarManager.isPlaying;\n }\n\n onIntroStartTourClicked() {\n this.events.emit(\"introStartTourClicked\", {}, this.buildEventContext());\n this.finishIntro();\n }\n\n onIntroCloseTourClicked() {\n this.events.emit(\"introCloseTourClicked\", {}, this.buildEventContext());\n this.dismissTour();\n }\n\n onIntroPostponeTourClicked() {\n this.events.emit(\"introPostponeTourClicked\", {}, this.buildEventContext());\n this.finishIntro();\n this.suspendTour(\"userAction\");\n }\n\n private buildFeedbackURLParameter() {\n const payload = {\n user_id: store.pyneClient.currentUser?.id,\n anonymous_id: store.pyneClient.anonymousId ?? undefined,\n session_id: this.sessionId,\n guide_id: this.guideId,\n organization_id: store.currentGuide?.organization_id,\n metadata: {\n stepIndex: this.flowState.currentStepIndex,\n },\n source: \"widget\",\n };\n\n const stringPayload = JSON.stringify(payload);\n try {\n const base64Payload = window.btoa(stringPayload);\n return base64Payload;\n } catch (error) {\n console.error(\"Error encoding payload\", error);\n return null;\n }\n }\n\n onGiveFeedbackClicked() {\n window.open(\n `https://dashboard.pyne.ai/feedback?app_id=${store.pyneSettings.app_id}&d=${this.buildFeedbackURLParameter()}`,\n \"_blank\"\n );\n this.events.emit(\"feedbackClicked\", {}, this.buildEventContext());\n }\n\n private clear() {\n this.stopGlobalEventBusMiddleware?.();\n this.stopListeningPageUrlChange?.();\n }\n\n private calculateStepOrder(sections: Section[], currentStep: Step) {\n const steps = sections.flatMap((section) => section.steps);\n const idx = steps.findIndex((step) => step.id === currentStep.id);\n return idx !== -1 ? idx : 0;\n }\n\n private isLastStepInTourFlow(step: Step) {\n const lastSection = this.tourFlow.sections[this.tourFlow.sections.length - 1];\n const lastStep = lastSection.steps[lastSection.steps.length - 1];\n return step.id === lastStep.id;\n }\n\n private calculateTourProgress(currentStepOrder: number) {\n const totalSteps = this.tourFlow.sections.reduce((acc, section) => acc + section.steps.length, 0);\n return (currentStepOrder / totalSteps) * 100;\n }\n\n private buildEventContext(pos?: FlowPosition): TourPlaybackEventContext {\n const stepIndex = pos ? pos.currentStepIndex : this.flowState.currentStepIndex;\n const sectionIndex = pos ? pos.currentSectionIndex : this.flowState.currentSectionIndex;\n\n const currentFlow = pos ? this.flows[pos.flowKey] : this.currentFlow;\n const currentSection = pos ? currentFlow?.sections[pos.currentSectionIndex] : this.currentSection;\n const currentStep = pos ? currentSection?.steps[pos.currentStepIndex] : this.currentStep;\n\n const currentStepOrder =\n currentFlow && currentStep ? this.calculateStepOrder(currentFlow.sections, currentStep) : 0;\n const tourProgress = this.currentFlowKey === \"tour\" ? this.calculateTourProgress(currentStepOrder) : 0;\n\n return {\n totalSteps: currentFlow?.sections.reduce((acc, section) => acc + section.steps.length, 0) ?? 0,\n isCheckpoint: currentStep?.attributes.isCheckpoint ?? false,\n flowKey: currentFlow?.key ?? \"\",\n stepId: currentStep?.id ?? \"\",\n stepType: currentStep?.attributes.type ?? \"\",\n currentMediaDuration: currentSection?.mediaDuration ?? 0,\n stepOrder: currentStepOrder,\n stepIndex: stepIndex,\n sectionIndex: sectionIndex,\n totalSectionSteps: currentSection?.steps.length ?? 0,\n time: this.currentTime,\n totalSections: this.tourFlow.sections.length,\n tourPlaybackVersion: this.tourPlayback.version,\n tourProgress: tourProgress,\n startedAt: this.startedAt,\n sessionId: this.sessionId ?? \"\",\n };\n }\n\n get nextSteps() {\n const steps = this.tourFlow.sections.flatMap((section) => section.steps);\n const currentStepIndex = steps.findIndex((step) => step.id === this.currentStep?.id);\n if (currentStepIndex === -1) return steps;\n\n return steps.slice(currentStepIndex + 1);\n }\n\n get avatarBackgroundPreviewGifUrl() {\n return this.pyneSettings.avatarBackgroundPreviewGifUrl ?? this.tourPlayback.previewGifUrl;\n }\n}\n\nexport const AUDIO_ONLY_AVATAR_IMG = `https://base.pyne.ai/storage/v1/object/public/tour-assets/v2/og:96091ece-f265-4685-a8ad-cc9395ec1f5e/g:cc2676a6-e10a-4892-8331-1806cab64e4f/3f43961995cd49e79802b7b768b2f51b/video.gif`;\nexport const AUDIO_ONLY_MINIMIZED_AVATAR_IMG =\n \"https://base.pyne.ai/storage/v1/object/public/tour-assets/v2/og:96091ece-f265-4685-a8ad-cc9395ec1f5e/g:cc2676a6-e10a-4892-8331-1806cab64e4f/3f43961995cd49e79802b7b768b2f51b/thumbnail.jpg\";\n","import { Guide } from \"@common/models\";\nimport { TourPlaybackManager } from \"./tourPlayback\";\n\nexport interface TourLifecycleManagerEvents {\n tourInitialized: { guide: Guide; tour: TourPlaybackManager };\n tourStarted: { guide: Guide };\n tourFinished: { guide: Guide };\n tourTerminated: { guide: Guide };\n tourDismissed: { guide: Guide };\n}\n\nexport type TourLifecycleEventContext = {\n guide?: Guide;\n};\n\nexport const TourLifecycleNamespace = \"tourLifecycle\" as const;\n","import { Guide } from \"@common/models\";\nimport { log } from \"../log\";\nimport { GuideScheduler, GuideScheduleReason } from \"./guideScheduler\";\nimport { TourPlaybackManager } from \"./tourPlayback\";\nimport { makeAutoObservable } from \"mobx\";\nimport { PersistentStorage } from \"./persistent-storage/storage\";\nimport { TourStartManager, TourStartStrategy } from \"./tourStartManager\";\nimport { globalEventBus } from \"../events/eventBus\";\nimport {\n TourLifecycleEventContext,\n TourLifecycleManagerEvents,\n TourLifecycleNamespace,\n} from \"./tourLifecycleManager.events\";\nimport { EventEmitter } from \"../events/eventEmitter\";\nimport { TabManager } from \"./tabManager\";\nimport { PyneSettings } from \"@common/schemas\";\nimport { TourState } from \"./persistent-storage/tourState\";\nimport { TourSession, TourSessionManager } from \"./tourSessionManager\";\n\nexport interface TourLifecycleManagerParams {\n pyneSettings: PyneSettings;\n guideScheduler: GuideScheduler;\n storage: PersistentStorage;\n tourStartManager: TourStartManager;\n tabManager: TabManager;\n tourSessionManager: TourSessionManager;\n previewGuideId?: string;\n skipBlobMediaPreload?: boolean;\n mediaPlaybackRate?: number;\n}\n\nexport type TourTerminateReason =\n | \"session_expired\"\n | \"trigger_from_debugger\"\n | \"trigger_from_pyne_client\"\n | \"tour_finished\"\n | \"tour_dismissed\"\n | \"restart_preview\"\n | \"close_preview\";\n\nexport class TourLifecycleManager {\n private pyneSettings: PyneSettings;\n guideScheduler: GuideScheduler;\n private tabManager: TabManager;\n private storage: PersistentStorage;\n public tourStartManager: TourStartManager;\n public currentGuide?: Guide;\n public currentTour?: TourPlaybackManager;\n public lastTourStartStrategy?: TourStartStrategy;\n private tourSessionManager: TourSessionManager;\n private tourSwitched = false;\n private preventPauseOnTabChange = false;\n public status: \"initialized\" | \"playingTour\" | \"tourFinished\" = \"initialized\";\n public events = new EventEmitter<\n typeof TourLifecycleNamespace,\n TourLifecycleManagerEvents,\n TourLifecycleEventContext\n >(TourLifecycleNamespace);\n private skipBlobMediaPreload?: boolean;\n private mediaPlaybackRate?: number;\n private eventEnricherMiddlewareStopFn?: () => void;\n\n constructor({\n pyneSettings,\n guideScheduler,\n storage,\n tourStartManager,\n tabManager,\n tourSessionManager,\n skipBlobMediaPreload,\n mediaPlaybackRate,\n }: TourLifecycleManagerParams) {\n makeAutoObservable(this);\n\n this.storage = storage;\n this.pyneSettings = pyneSettings;\n this.tourStartManager = tourStartManager;\n this.tabManager = tabManager;\n this.skipBlobMediaPreload = skipBlobMediaPreload;\n this.mediaPlaybackRate = mediaPlaybackRate;\n this.tourSessionManager = tourSessionManager;\n this.storage.sessionState.setVisitedAt();\n\n this.guideScheduler = guideScheduler;\n this.guideScheduler.events.on(\"guideScheduled\", ({ payload: { guide, scheduleReason, tourState } }) => {\n this.startTour({ guide, scheduleReason, tourState });\n });\n\n this.tabManager.events.on(\"currentTabActivated\", () => {\n this.startScheduler();\n });\n\n this.tabManager.events.on(\"currentTabInactivated\", () => {\n this.stopScheduler();\n if (this.preventPauseOnTabChange) {\n this.preventPauseOnTabChange = false;\n return;\n }\n this.currentTour?.pauseTour();\n });\n\n this.tabManager.events.on(\"otherTabTookoverTheTour\", () => {\n this.currentTour?.suspendTour(\"tourPlayingOnOtherTab\");\n });\n\n this.tourSessionManager.events.on(\"tourSessionExpired\", ({ payload: { sessionId } }) => {\n if (this.tabManager.amIActive()) {\n this.terminateCurrentTourAndLookForOthers(\"session_expired\");\n } else {\n this.terminateCurrentTour(\"session_expired\");\n }\n });\n }\n\n get isTourPlaying() {\n return (\n !!this.currentTour &&\n !(\n this.currentTour.status === \"finished\" ||\n this.currentTour.status === \"terminated\" ||\n this.currentTour.status === \"dismissed\" ||\n this.currentTour.status === undefined\n )\n );\n }\n\n terminateCurrentTour(reason: TourTerminateReason) {\n if (!this.currentTour) {\n return;\n }\n\n this.tourSessionManager.terminateTourSession(reason);\n this.currentTour?.terminateTour();\n this.clearCurrentTour();\n }\n\n terminateCurrentTourAndLookForOthers(terminateReason: TourTerminateReason) {\n this.terminateCurrentTour(terminateReason);\n this.lookForOtherGuides();\n }\n\n start() {\n log(\"starting tour lifecycle manager\");\n this.startScheduler();\n }\n\n private startScheduler() {\n if (!this.tabManager.amIActive()) {\n return;\n }\n\n this.guideScheduler.start();\n }\n\n stop() {\n this.guideScheduler.stop();\n }\n\n // if we cause a focus change, we should prevent the tour from pausing\n handleQuestionChoiceSelected(choiceType: string) {\n if (choiceType === \"link\") {\n this.preventPauseOnTabChange = true;\n }\n }\n\n async terminateCurrentTourAndStartNewTour(\n guide: Guide,\n reason: GuideScheduleReason,\n terminateReason: TourTerminateReason,\n options?: { tourStartStrategy?: TourStartStrategy }\n ) {\n this.terminateCurrentTour(terminateReason);\n await this.startTour({ guide, scheduleReason: reason }, options);\n }\n\n async startTour(\n { guide, scheduleReason, tourState }: { guide: Guide; scheduleReason: GuideScheduleReason; tourState?: TourState },\n options?: { tourStartStrategy?: TourStartStrategy }\n ) {\n if (this.currentTour) {\n return;\n }\n\n this.stopScheduler();\n\n this.eventEnricherMiddlewareStopFn?.();\n this.eventEnricherMiddlewareStopFn = globalEventBus.use(\"*\", (context) => {\n return { guide, ...context };\n });\n\n if (!guide.tour_playback) {\n throw new Error(\"Guide does not have tour playback data\");\n }\n\n const tourStartStrategy = await this.tourStartManager.decideStrategy(\n this.tabManager.tabId,\n guide.tour_playback,\n tourState\n );\n this.lastTourStartStrategy = tourStartStrategy;\n\n const sessionInfo = this.tourSessionManager.initializeTourSession(scheduleReason);\n\n const tourPlaybackManager = this.buildTourPlaybackManager(\n guide,\n options?.tourStartStrategy ?? tourStartStrategy,\n sessionInfo\n );\n this.currentGuide = guide;\n this.currentTour = tourPlaybackManager;\n\n tourPlaybackManager.events.on(\"started\", () => this.events.emit(\"tourStarted\", { guide }));\n\n tourPlaybackManager.events.on(\"finished\", () => this.events.emit(\"tourFinished\", { guide }));\n\n tourPlaybackManager.events.on(\"terminated\", () => {\n this.events.emit(\"tourTerminated\", { guide });\n });\n\n tourPlaybackManager.events.on(\"dismissed\", () => {\n this.events.emit(\"tourDismissed\", { guide });\n });\n\n this.events.emit(\"tourInitialized\", { guide, tour: tourPlaybackManager });\n\n log(\"starting tour\");\n\n tourPlaybackManager.start();\n this.tourSwitched = false;\n this.status = \"playingTour\";\n }\n\n buildTourPlaybackManager(\n guide: Guide,\n tourStartStrategy: TourStartStrategy,\n session: TourSession\n ): TourPlaybackManager {\n if (!guide.tour_playback) {\n throw new Error(\"Guide does not have tour playback data\");\n }\n\n const tourPlaybackManager = new TourPlaybackManager({\n pyneSettings: this.pyneSettings,\n guideId: guide.id,\n tourPlayback: guide.tour_playback,\n startStrategy: tourStartStrategy,\n settings: guide.settings,\n shouldAutoPlayFirstStep:\n guide.settings.should_auto_play_first_step || this.tourSwitched || tourStartStrategy.type !== \"startOver\",\n avatarStateStorage: this.storage.avatarState,\n tourStateStorage: this.storage.tourState,\n userStateStorage: this.storage.userState,\n skipBlobMediaPreload: this.skipBlobMediaPreload,\n mediaPlaybackRate: this.mediaPlaybackRate,\n tabId: this.tabManager.tabId,\n sessionId: session.sessionId,\n startedAt: session.startedAt,\n });\n\n tourPlaybackManager.events.on(\"finished\", () => {\n this.handleTourFinished();\n });\n\n tourPlaybackManager.events.on(\"finishCriteriaMet\", () => {\n this.handleTourFinishCriteriaMet();\n });\n\n tourPlaybackManager.events.on(\"dismissed\", () => {\n this.handleTourDismissed();\n });\n\n tourPlaybackManager.events.on(\"questionChoiceSelected\", ({ payload: { choiceType } }) => {\n this.handleQuestionChoiceSelected(choiceType);\n });\n\n tourPlaybackManager.events.on(\"tourSwitched\", ({ payload: { guideId } }) => {\n this.handleTourSwitch(guideId);\n });\n\n return tourPlaybackManager;\n }\n\n dismissCurrentTour() {\n this.currentTour?.dismissTour();\n }\n\n clearState() {\n this.storage.clearTourRelatedState();\n }\n\n private handleTourSwitch(guideId: string) {\n log(\"tour switch\", guideId);\n this.currentTour?.finishTour();\n this.tourSwitched = true;\n this.guideScheduler.switchGuide(guideId, \"trigger_from_other_tour\");\n }\n\n forceStartTour(guideId: string, reason: \"trigger_from_pyne_client\", terminateReason: TourTerminateReason) {\n if (this.currentGuide?.id === guideId) {\n return;\n }\n\n this.terminateCurrentTour(terminateReason);\n this.guideScheduler.switchGuide(guideId, reason);\n }\n\n private handleTourFinished() {\n log(\"tour finished\");\n this.terminateCurrentTourAndLookForOthers(\"tour_finished\");\n this.status = \"tourFinished\";\n }\n\n private handleTourFinishCriteriaMet() {\n log(\"tour finish criteria met\");\n this.storage.userState.addFinishedGuide(this.currentGuide!.id);\n }\n\n private handleTourDismissed() {\n log(\"tour dismissed\");\n this.storage.userState.addDismissedGuide(this.currentGuide!.id);\n this.terminateCurrentTourAndLookForOthers(\"tour_dismissed\");\n this.status = \"tourFinished\";\n }\n\n private clearCurrentTour() {\n this.currentGuide = undefined;\n this.currentTour = undefined;\n this.lastTourStartStrategy = undefined;\n this.storage.clearTourState();\n }\n\n private lookForOtherGuides() {\n this.clearCurrentTour();\n this.guideScheduler.clearCurrentGuide();\n this.startScheduler();\n }\n\n private stopScheduler() {\n this.guideScheduler.stop();\n }\n}\n","import { makeAutoObservable } from \"mobx\";\nimport { log } from \"./lib/log\";\nimport { BasicEvent, trackAnyEvent } from \"./lib/tracking/track\";\nimport { uuid } from \"./lib/utils\";\nimport type { RootStore } from \"./store\";\nimport { globalEventBus } from \"./lib/events/eventBus\";\n\ntype PyneTourLifecycleEventPayload = {\n id: string;\n};\n\n// This class represents the public API of the Pyne script.\nexport class PyneClient {\n currentUser: { id: string; traits: Record } | null = null;\n anonymousId: string | null = null;\n isReady = false;\n readyCallbacks: Function[] = [];\n\n constructor(public rootStore: RootStore) {\n this.anonymousId = PyneClient.getAnonymousId();\n this.currentUser = PyneClient.getSafedCurrentUser();\n this.runCommand = this.runCommand.bind(this);\n makeAutoObservable(this, { rootStore: false });\n }\n\n get currentUserData() {\n return {\n id: this.currentUser?.id,\n ...this.currentUser?.traits,\n anonymousId: this.anonymousId,\n };\n }\n\n PUBLIC_METHODS = [\n \"identify\",\n \"track\",\n \"terminateCurrentTour\",\n \"startTour\",\n \"onTourStarted\",\n \"onTourFinished\",\n \"onTourTerminated\",\n \"onTourSuspended\",\n \"onTourUnsuspended\",\n \"onTourDismissed\",\n \"onUserMinimizedAvatar\",\n \"onUserExpandedAvatar\",\n \"ready\",\n ];\n\n async runCommand(method: string, ...args: unknown[]) {\n if (!this.PUBLIC_METHODS.includes(method)) throw new Error(`Unknown method ${method}`);\n // @ts-ignore\n return this[method](...args);\n }\n\n // Identify lets you provide a unique ID and traits about a user.\n // Usage: window.pyne('identify', \"some-user-id-123\", { name: \"Michael Bolton\", email: \"mbolton@initech\" });\n // To delete user information (e.g. when a user logs out), you can call: `window.pyne('identify', null)`\n async identify(userId: string | null, traits: Record) {\n log(\"identify\", userId, traits);\n this.currentUser = userId ? { id: userId, traits } : null;\n PyneClient.safeCurrentUser(this.currentUser);\n }\n\n static getAnonymousId() {\n let id = localStorage.getItem(\"pyne-anonymous-id\");\n if (!id) {\n id = uuid();\n localStorage.setItem(\"pyne-anonymous-id\", id);\n }\n return id;\n }\n\n static safeCurrentUser(userData: typeof PyneClient.prototype.currentUser) {\n // localStorage.setItem(\"pyne-current-user\", JSON.stringify(userData));\n }\n\n static getSafedCurrentUser() {\n return null;\n // const userData = localStorage.getItem(\"pyne-current-user\");\n // try {\n // return userData ? JSON.parse(userData) : null;\n // } catch (e) {\n // console.error(e);\n // return null;\n // }\n }\n\n async track(eventName: T[\"event\"], eventData: Exclude) {\n log(\"track\", eventData);\n trackAnyEvent(\n {\n event: eventName,\n properties: {\n ...eventData,\n },\n },\n {\n user_id: this.currentUser?.id,\n anonymous_id: this.anonymousId ?? undefined,\n }\n );\n }\n\n startTour(guideId: string) {\n this.rootStore.tourLifecycleManager.forceStartTour(guideId, \"trigger_from_pyne_client\", \"trigger_from_pyne_client\");\n }\n\n terminateCurrentTour() {\n this.rootStore.tourLifecycleManager.terminateCurrentTourAndLookForOthers(\"trigger_from_pyne_client\");\n }\n\n onTourStarted(callback: (payload: PyneTourLifecycleEventPayload) => void) {\n this.rootStore.tourLifecycleManager.events.on(\"tourStarted\", ({ payload: { guide } }) => {\n callback({ id: guide.id });\n });\n }\n\n onTourFinished(callback: (payload: PyneTourLifecycleEventPayload) => void) {\n this.rootStore.tourLifecycleManager.events.on(\"tourFinished\", ({ payload: { guide } }) => {\n callback({ id: guide.id });\n });\n }\n\n onTourTerminated(callback: (payload: PyneTourLifecycleEventPayload) => void) {\n this.rootStore.tourLifecycleManager.events.on(\"tourTerminated\", ({ payload: { guide } }) => {\n callback({ id: guide.id });\n });\n }\n\n onTourSuspended(callback: (payload: { id: string }) => void) {\n globalEventBus.on(\"tourPlayback.suspended\", ({ context: { guide } }) => {\n if (!guide) return;\n callback({ id: guide.id });\n });\n }\n\n onTourUnsuspended(callback: (payload: { id: string }) => void) {\n globalEventBus.on(\"tourPlayback.unsuspended\", ({ context: { guide } }) => {\n if (!guide) return;\n callback({ id: guide.id });\n });\n }\n\n onTourDismissed(callback: (payload: { id: string }) => void) {\n globalEventBus.on(\"tourLifecycle.tourDismissed\", ({ payload: { guide } }) => {\n callback({ id: guide.id });\n });\n }\n\n onUserMinimizedAvatar(callback: (payload: { id: string }) => void) {\n globalEventBus.on(\"avatar.minimizeClicked\", ({ context: { guide } }) => {\n if (!guide) return;\n callback({ id: guide.id });\n });\n }\n\n onUserExpandedAvatar(callback: (payload: { id: string }) => void) {\n globalEventBus.on(\"avatar.expandClicked\", ({ context: { guide } }) => {\n if (!guide) return;\n callback({ id: guide.id });\n });\n }\n\n ready(callback: () => void) {\n if (this.isReady) {\n setTimeout(() => callback(), 0);\n } else {\n this.readyCallbacks.push(callback);\n }\n }\n\n async runQueuedCommands() {\n const queue = window.pyne.q ?? [];\n\n while (queue.length) {\n const [method, ...args] = queue.shift()!;\n await this.runCommand(method, ...args);\n }\n\n (window.pyne as any).c = ([method, ...args]: any[]) => this.runCommand(method, ...args);\n this.isReady = true;\n this.runReadyCallbacks();\n }\n\n runReadyCallbacks() {\n for (const cb of this.readyCallbacks) {\n setTimeout(() => cb(), 0);\n }\n }\n}\n","import { calculateLocalTimeConditionDelta, calculateTimeoutOnCurrentPageConditionDelta, checkUrlCondition, } from \"./audience-check\";\nexport var TargetingErrorCodes;\n(function (TargetingErrorCodes) {\n TargetingErrorCodes[\"WHERE_NOT_MATCHING\"] = \"WHERE_NOT_MATCHING\";\n TargetingErrorCodes[\"WHEN_NOT_MATCHING\"] = \"WHEN_NOT_MATCHING\";\n TargetingErrorCodes[\"WHO_NOT_MATCHING\"] = \"WHO_NOT_MATCHING\";\n TargetingErrorCodes[\"NO_SECTIONS\"] = \"NO_SECTIONS\";\n TargetingErrorCodes[\"NOT_GENERATED\"] = \"NOT_GENERATED\";\n TargetingErrorCodes[\"NOT_TARGETED\"] = \"NOT_TARGETED\";\n TargetingErrorCodes[\"NOT_PUBLISHED\"] = \"NOT_PUBLISHED\";\n TargetingErrorCodes[\"DISMISSED\"] = \"DISMISSED\";\n TargetingErrorCodes[\"FINISHED\"] = \"FINISHED\";\n TargetingErrorCodes[\"EXPIRED\"] = \"EXPIRED\";\n})(TargetingErrorCodes || (TargetingErrorCodes = {}));\nexport class ClientGuideTargetingEvaluator {\n url;\n selectorObserver;\n localTime;\n firstTimeVisitedAt;\n constructor({ url, selectorObserver, localTime, firstTimeVisitedAt, }) {\n this.url = url;\n this.selectorObserver = selectorObserver;\n this.localTime = localTime;\n this.firstTimeVisitedAt = firstTimeVisitedAt;\n }\n async evaluate(guide) {\n const whereMatchResults = await this.checkWhereConditions(guide.targeting, guide.settings);\n const isWhereMatching = whereMatchResults.every((match) => match.result);\n const whereMatch = {\n predicates: whereMatchResults,\n result: isWhereMatching,\n message: isWhereMatching ? undefined : TargetingErrorCodes.WHERE_NOT_MATCHING,\n };\n const whenMatchResults = await this.checkWhenConditions(guide.targeting);\n const isWhenMatching = whenMatchResults.every((match) => match.result);\n const whenMatch = {\n predicates: whenMatchResults,\n result: isWhenMatching,\n message: isWhenMatching ? undefined : TargetingErrorCodes.WHEN_NOT_MATCHING,\n };\n const res = {\n ...guide.matchEvaulation,\n whereMatch,\n whenMatch,\n isTargetingEnabled: guide.targeting.isEnabled,\n isWhereTargeted: whereMatch.result,\n isWhenTargeted: whenMatch.result,\n result: guide.matchEvaulation.prefilter.result && whereMatch.result && whenMatch.result,\n message: guide.matchEvaulation.prefilter.message ?? whereMatch.message ?? whenMatch.message,\n };\n return res;\n }\n async checkWhereConditions(targeting, settings) {\n const conditions = (targeting?.where ?? []);\n const matchResults = [];\n for (const condition of conditions) {\n if (condition.left_operand === \"url\") {\n const isUrlConditionSatisfied = checkUrlCondition(condition, this.url);\n matchResults.push({\n predicate: condition,\n result: isUrlConditionSatisfied,\n value: this.url,\n });\n }\n else if (condition.left_operand === \"selector\") {\n const selector = condition.right_operand;\n if (condition.operator === \"not_exists\") {\n const timeout = settings.selector_timeout_settings?.not_exist_timeout ?? 3000;\n const isElementExists = await this.selectorObserver.isAvailable(selector, timeout);\n matchResults.push({\n predicate: condition,\n result: !isElementExists,\n value: selector,\n });\n }\n else if (condition.operator === \"exists\") {\n const timeout = settings.selector_timeout_settings?.exist_timeout ?? 3000;\n const isElementExists = await this.selectorObserver.isAvailable(selector, timeout);\n matchResults.push({\n predicate: condition,\n result: isElementExists,\n value: selector,\n });\n }\n }\n }\n return matchResults;\n }\n // Filter out guides that we don't need to evaluate anymore\n static prefilterGuide(params) {\n const { guide, dismissedGuideIds, finishedGuideIds, expiredGuideIds } = params;\n if (!guide.matchEvaulation.isGenerated) {\n return { result: false, message: TargetingErrorCodes.NOT_GENERATED };\n }\n if (!guide.matchEvaulation.isWhoTargeted) {\n return { result: false, message: TargetingErrorCodes.WHO_NOT_MATCHING };\n }\n if (!guide.matchEvaulation.isPublished) {\n return { result: false, message: TargetingErrorCodes.NOT_PUBLISHED };\n }\n if (dismissedGuideIds.includes(guide.id)) {\n return { result: false, message: TargetingErrorCodes.DISMISSED, params: { dismissedGuideIds, finishedGuideIds } };\n }\n if (finishedGuideIds.includes(guide.id)) {\n return { result: false, message: TargetingErrorCodes.FINISHED, params: { dismissedGuideIds, finishedGuideIds } };\n }\n if (expiredGuideIds.includes(guide.id)) {\n return {\n result: false,\n message: TargetingErrorCodes.EXPIRED,\n params: { dismissedGuideIds, finishedGuideIds, expiredGuideIds },\n };\n }\n return {\n result: true,\n message: undefined,\n params: { dismissedGuideIds, finishedGuideIds, expiredGuideIds },\n };\n }\n async checkWhenConditions(targeting) {\n const conditions = (targeting?.when ?? []);\n const matchResults = [];\n for (const condition of conditions) {\n if (condition.left_operand === \"local_time_at\") {\n const timeDelta = calculateLocalTimeConditionDelta(condition, this.localTime);\n switch (condition.operator) {\n case \"before\":\n matchResults.push({\n predicate: condition,\n result: timeDelta > 0,\n value: timeDelta.toString(),\n });\n break;\n case \"after\":\n matchResults.push({\n predicate: condition,\n result: timeDelta <= 0,\n value: timeDelta.toString(),\n });\n break;\n }\n }\n else if (condition.left_operand === \"time_on_current_page\") {\n const timeDelta = calculateTimeoutOnCurrentPageConditionDelta(condition, this.firstTimeVisitedAt, this.localTime);\n matchResults.push({\n predicate: condition,\n result: timeDelta >= condition.right_operand * 1000,\n value: timeDelta.toString(),\n });\n }\n }\n return matchResults;\n }\n}\n","import { throttle } from \"lodash-es\";\nimport { makeAutoObservable, reaction } from \"mobx\";\nimport { findElement } from \"../lib/element\";\n\nexport type Selector = { target: string };\n\nexport class SelectorObserver {\n matches: Record = {};\n private selectors: Selector[] = [];\n private selectorSearchStartTimes: Map = new Map();\n checkInterval: number = 1000;\n\n constructor() {\n makeAutoObservable(this);\n\n reaction(\n () => this.selectors,\n () => {\n // FIX: this is called after isAvailable is called\n // This causes selector search not started error on initial isAvailable call\n this.findAllSelectors();\n }\n );\n\n this.observe();\n }\n\n update(selectors: Selector[]) {\n this.selectors = selectors;\n }\n\n get foundSelectors() {\n return Object.keys(this.matches);\n }\n\n findThisElementsThrottled = throttle(() => {\n this.findAllSelectors();\n }, 100);\n\n findAllSelectors() {\n for (const selector of this.selectors) {\n this.findSelector(selector.target);\n }\n }\n\n findSelector(selector: string) {\n const now = Date.now();\n if (!this.selectorSearchStartTimes.has(selector)) {\n this.selectorSearchStartTimes.set(selector, now);\n }\n\n const el = findElement(selector);\n if (el) {\n this.matches[selector] = { element: el };\n } else {\n if (this.matches[selector]) {\n delete this.matches[selector];\n }\n }\n }\n\n observe() {\n this.findThisElementsThrottled();\n\n const observer = new MutationObserver(() => {\n this.findThisElementsThrottled();\n });\n\n observer.observe(document, {\n childList: true,\n subtree: true,\n attributes: true,\n characterData: true,\n });\n\n const intervalId = setInterval(() => {\n this.findThisElementsThrottled();\n }, this.checkInterval);\n\n return () => {\n // cleanup\n observer.disconnect();\n clearInterval(intervalId);\n };\n }\n\n isSelectorFound(selector: string) {\n return !!this.matches[selector];\n }\n\n waitUntilSelectorFound(selector: string, timeout: number): Promise {\n return new Promise((resolve, _reject) => {\n const startTime = Date.now();\n const intervalId = setInterval(() => {\n if (this.isSelectorFound(selector)) {\n clearInterval(intervalId);\n resolve(this.matches[selector].element);\n }\n\n const elapsedTime = Date.now() - startTime;\n if (elapsedTime > timeout) {\n clearInterval(intervalId);\n resolve(null);\n }\n }, 100);\n });\n }\n\n async isAvailable(selector: string, timeout: number): Promise {\n if (this.isSelectorFound(selector)) {\n return Promise.resolve(true);\n }\n\n const startTime = this.selectorSearchStartTimes.get(selector);\n const isSearchNotStartedYet = !startTime;\n if (isSearchNotStartedYet) {\n this.findSelector(selector);\n await this.waitUntilSelectorFound(selector, timeout);\n return Promise.resolve(this.isSelectorFound(selector));\n }\n\n const elapsedTime = Date.now() - startTime;\n const remainingTime = timeout - elapsedTime;\n\n const isTimeoutPassed = remainingTime <= 0;\n if (isTimeoutPassed) {\n return Promise.resolve(this.isSelectorFound(selector));\n }\n\n await this.waitUntilSelectorFound(selector, remainingTime);\n return this.isSelectorFound(selector);\n }\n}\n","import { autorun, makeAutoObservable, reaction, toJS } from \"mobx\";\nimport { ClientGuideTargetingEvaluator } from \"@common/targeting/ClientGuideTargetingEvaluator\";\nimport { pageInfo } from \"./PageInfo\";\nimport { Selector, SelectorObserver } from \"./SelectorObserver\";\nimport { PersistentStorage } from \"@/lib/tour/persistent-storage/storage\";\nimport { GuideRegistry } from \"./GuideRegistry\";\nimport { GuideClientMatchEvaluation } from \"@common/targeting/audience-check\";\n\ninterface SyncManager {\n isSettled: boolean;\n}\n\nexport interface GuideTargetingEvaluatorParams {\n syncManager: SyncManager;\n storage: PersistentStorage;\n guideRegistry: GuideRegistry;\n}\n\nexport type GuideEvaluationResultWithOrder = {\n guideId: string;\n details: GuideClientMatchEvaluation;\n matchOrder: number;\n};\n\n// This class is used to pick a guide based on the targeting conditions.\n// It checks for elements in a page and url\nexport class GuideTargetingEvaluator {\n selectorObserver = new SelectorObserver();\n evaluatedGuides: GuideEvaluationResultWithOrder[] = [];\n storage: PersistentStorage;\n page = pageInfo;\n syncManager: SyncManager;\n guideRegistry: GuideRegistry;\n\n constructor({ syncManager, guideRegistry, storage }: GuideTargetingEvaluatorParams) {\n makeAutoObservable(this);\n\n this.syncManager = syncManager;\n this.storage = storage;\n this.guideRegistry = guideRegistry;\n\n autorun(() => {\n // Update selectorObserver whenever the selectors change\n this.selectorObserver.update(this.selectors);\n });\n\n reaction(\n () => [this.selectorObserver.foundSelectors, this.prefilteredGuides, this.page.url],\n () => {\n this.evaluateGuides();\n }\n );\n }\n\n get allGuides() {\n if (!this.syncManager.isSettled || !this.storage.userState.isHydrated) return [];\n\n const dismissedGuideIds = this.storage.userState.dismissedTourGuideIds;\n const finishedGuideIds = this.storage.userState.finishedTourGuideIds;\n const expiredGuideIds = this.storage.sessionState.expiredTourGuideIds;\n return this.guideRegistry.guides.map((guide) => {\n const prefilterResult = ClientGuideTargetingEvaluator.prefilterGuide({\n guide,\n dismissedGuideIds,\n finishedGuideIds,\n expiredGuideIds,\n });\n\n return {\n id: guide.id,\n targeting: guide.targeting,\n settings: guide.settings,\n matchEvaulation: {\n ...guide.matchEvaulation,\n prefilter: prefilterResult,\n result: false,\n },\n };\n });\n }\n\n get prefilteredGuides() {\n return this.allGuides.filter((guide) => guide.matchEvaulation.prefilter.result);\n }\n\n get selectors() {\n const selectors: Selector[] = [];\n for (const guide of this.prefilteredGuides) {\n guide.targeting?.where?.forEach((condition) => {\n if (condition.left_operand === \"selector\") {\n selectors.push({ target: condition.right_operand });\n }\n });\n }\n\n return selectors;\n }\n\n evaluationIndex = 0;\n\n async evaluateGuides() {\n if (!this.syncManager.isSettled) return [];\n const currentEvaluationIndex = ++this.evaluationIndex;\n\n const evaluator = new ClientGuideTargetingEvaluator({\n url: this.page.url,\n selectorObserver: this.selectorObserver,\n localTime: new Date(),\n firstTimeVisitedAt: new Date(this.storage.sessionState.getVisitedAt() as number),\n });\n\n this.evaluatedGuides = this.allGuides.map(this.buildEvaluatingGuide);\n\n let matchOrder = 1;\n\n const evaluations = this.allGuides.map(async (guide, index) => {\n const matchEvaulation = await evaluator.evaluate(guide);\n const order = matchEvaulation.result ? matchOrder++ : -1;\n\n const evaluatedGuide: GuideEvaluationResultWithOrder = {\n guideId: guide.id,\n details: matchEvaulation,\n matchOrder: order,\n };\n\n // Most of the time we don't receive user id initially and dismissed/finished guides will be empty if local storage is cleared\n // Whenever client calls identify with user id, guides are re-evaluated with dismissed/finished guides that restored from server\n // Following check prevents evaluation results from being stored if more recent evaluation is in progress\n // Otherwise, dismissed/finished guides will be started immediately without waiting for recent evaluation to finish\n const isMostRecentEvaluation = this.evaluationIndex === currentEvaluationIndex;\n if (isMostRecentEvaluation) {\n this.evaluatedGuides[index] = evaluatedGuide;\n }\n });\n\n await Promise.allSettled(evaluations);\n }\n\n buildEvaluatingGuide(guide: {\n id: string;\n targeting: { isEnabled?: boolean };\n matchEvaulation: GuideClientMatchEvaluation;\n }) {\n return {\n guideId: guide.id,\n details: {\n result: false,\n message: \"CLIENT_EVALUATING\",\n isGenerated: guide.matchEvaulation.isGenerated,\n isPublished: guide.matchEvaulation.isPublished,\n isWhoTargeted: guide.matchEvaulation.isWhoTargeted,\n prefilter: guide.matchEvaulation.prefilter,\n isTargetingEnabled: guide.targeting.isEnabled,\n },\n matchOrder: -1,\n };\n }\n\n get firstMatchingGuideId() {\n return (\n this.evaluatedGuides.find(\n (guide) => guide.details.result && guide.details.isPublished && guide.details.isTargetingEnabled\n )?.guideId ?? null\n );\n }\n\n findResultById(id: string) {\n return this.evaluatedGuides.find(({ guideId }) => guideId === id);\n }\n}\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nmodule.exports = listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nmodule.exports = eq;\n","var eq = require('./eq');\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nmodule.exports = assocIndexOf;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nmodule.exports = listCacheDelete;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nmodule.exports = listCacheGet;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nmodule.exports = listCacheHas;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nmodule.exports = listCacheSet;\n","var listCacheClear = require('./_listCacheClear'),\n listCacheDelete = require('./_listCacheDelete'),\n listCacheGet = require('./_listCacheGet'),\n listCacheHas = require('./_listCacheHas'),\n listCacheSet = require('./_listCacheSet');\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nmodule.exports = ListCache;\n","var ListCache = require('./_ListCache');\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nmodule.exports = stackClear;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nmodule.exports = stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nmodule.exports = stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nmodule.exports = stackHas;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nmodule.exports = freeGlobal;\n","var freeGlobal = require('./_freeGlobal');\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\nmodule.exports = root;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n","var Symbol = require('./_Symbol');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nmodule.exports = getRawTag;\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 nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nmodule.exports = objectToString;\n","var Symbol = require('./_Symbol'),\n getRawTag = require('./_getRawTag'),\n objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\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 != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","var baseGetTag = require('./_baseGetTag'),\n isObject = require('./isObject');\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\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 a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nmodule.exports = isFunction;\n","var root = require('./_root');\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nmodule.exports = coreJsData;\n","var coreJsData = require('./_coreJsData');\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nmodule.exports = isMasked;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nmodule.exports = toSource;\n","var isFunction = require('./isFunction'),\n isMasked = require('./_isMasked'),\n isObject = require('./isObject'),\n toSource = require('./_toSource');\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nmodule.exports = baseIsNative;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nmodule.exports = getValue;\n","var baseIsNative = require('./_baseIsNative'),\n getValue = require('./_getValue');\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nmodule.exports = getNative;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nmodule.exports = Map;\n","var getNative = require('./_getNative');\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nmodule.exports = nativeCreate;\n","var nativeCreate = require('./_nativeCreate');\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nmodule.exports = hashClear;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = hashDelete;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nmodule.exports = hashGet;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nmodule.exports = hashHas;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nmodule.exports = hashSet;\n","var hashClear = require('./_hashClear'),\n hashDelete = require('./_hashDelete'),\n hashGet = require('./_hashGet'),\n hashHas = require('./_hashHas'),\n hashSet = require('./_hashSet');\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nmodule.exports = Hash;\n","var Hash = require('./_Hash'),\n ListCache = require('./_ListCache'),\n Map = require('./_Map');\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nmodule.exports = mapCacheClear;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nmodule.exports = isKeyable;\n","var isKeyable = require('./_isKeyable');\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nmodule.exports = getMapData;\n","var getMapData = require('./_getMapData');\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = mapCacheDelete;\n","var getMapData = require('./_getMapData');\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nmodule.exports = mapCacheGet;\n","var getMapData = require('./_getMapData');\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nmodule.exports = mapCacheHas;\n","var getMapData = require('./_getMapData');\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nmodule.exports = mapCacheSet;\n","var mapCacheClear = require('./_mapCacheClear'),\n mapCacheDelete = require('./_mapCacheDelete'),\n mapCacheGet = require('./_mapCacheGet'),\n mapCacheHas = require('./_mapCacheHas'),\n mapCacheSet = require('./_mapCacheSet');\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nmodule.exports = MapCache;\n","var ListCache = require('./_ListCache'),\n Map = require('./_Map'),\n MapCache = require('./_MapCache');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nmodule.exports = stackSet;\n","var ListCache = require('./_ListCache'),\n stackClear = require('./_stackClear'),\n stackDelete = require('./_stackDelete'),\n stackGet = require('./_stackGet'),\n stackHas = require('./_stackHas'),\n stackSet = require('./_stackSet');\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nmodule.exports = Stack;\n","var getNative = require('./_getNative');\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nmodule.exports = defineProperty;\n","var defineProperty = require('./_defineProperty');\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nmodule.exports = baseAssignValue;\n","var baseAssignValue = require('./_baseAssignValue'),\n eq = require('./eq');\n\n/**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nmodule.exports = assignMergeValue;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nmodule.exports = createBaseFor;\n","var createBaseFor = require('./_createBaseFor');\n\n/**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\nvar baseFor = createBaseFor();\n\nmodule.exports = baseFor;\n","var root = require('./_root');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n}\n\nmodule.exports = cloneBuffer;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nmodule.exports = Uint8Array;\n","var Uint8Array = require('./_Uint8Array');\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\nmodule.exports = cloneArrayBuffer;\n","var cloneArrayBuffer = require('./_cloneArrayBuffer');\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nmodule.exports = cloneTypedArray;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nmodule.exports = copyArray;\n","var isObject = require('./isObject');\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nvar baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n}());\n\nmodule.exports = baseCreate;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nmodule.exports = overArg;\n","var overArg = require('./_overArg');\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nmodule.exports = getPrototype;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nmodule.exports = isPrototype;\n","var baseCreate = require('./_baseCreate'),\n getPrototype = require('./_getPrototype'),\n isPrototype = require('./_isPrototype');\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\nmodule.exports = initCloneObject;\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 != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nmodule.exports = baseIsArguments;\n","var baseIsArguments = require('./_baseIsArguments'),\n isObjectLike = require('./isObjectLike');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\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 `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nmodule.exports = isArguments;\n","/**\n * Checks if `value` is classified as an `Array` object.\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 array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nmodule.exports = isArray;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\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 valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nmodule.exports = isLength;\n","var isFunction = require('./isFunction'),\n isLength = require('./isLength');\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\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 array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nmodule.exports = isArrayLike;\n","var isArrayLike = require('./isArrayLike'),\n isObjectLike = require('./isObjectLike');\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an 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 an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\nmodule.exports = isArrayLikeObject;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = stubFalse;\n","var root = require('./_root'),\n stubFalse = require('./stubFalse');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nmodule.exports = isBuffer;\n","var baseGetTag = require('./_baseGetTag'),\n getPrototype = require('./_getPrototype'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n}\n\nmodule.exports = isPlainObject;\n","var baseGetTag = require('./_baseGetTag'),\n isLength = require('./isLength'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nmodule.exports = baseIsTypedArray;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nmodule.exports = baseUnary;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nmodule.exports = nodeUtil;\n","var baseIsTypedArray = require('./_baseIsTypedArray'),\n baseUnary = require('./_baseUnary'),\n nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nmodule.exports = isTypedArray;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nmodule.exports = safeGet;\n","var baseAssignValue = require('./_baseAssignValue'),\n eq = require('./eq');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nmodule.exports = assignValue;\n","var assignValue = require('./_assignValue'),\n baseAssignValue = require('./_baseAssignValue');\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n}\n\nmodule.exports = copyObject;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nmodule.exports = baseTimes;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nmodule.exports = isIndex;\n","var baseTimes = require('./_baseTimes'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isIndex = require('./_isIndex'),\n isTypedArray = require('./isTypedArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = arrayLikeKeys;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = nativeKeysIn;\n","var isObject = require('./isObject'),\n isPrototype = require('./_isPrototype'),\n nativeKeysIn = require('./_nativeKeysIn');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = baseKeysIn;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeysIn = require('./_baseKeysIn'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nmodule.exports = keysIn;\n","var copyObject = require('./_copyObject'),\n keysIn = require('./keysIn');\n\n/**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\nfunction toPlainObject(value) {\n return copyObject(value, keysIn(value));\n}\n\nmodule.exports = toPlainObject;\n","var assignMergeValue = require('./_assignMergeValue'),\n cloneBuffer = require('./_cloneBuffer'),\n cloneTypedArray = require('./_cloneTypedArray'),\n copyArray = require('./_copyArray'),\n initCloneObject = require('./_initCloneObject'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isArrayLikeObject = require('./isArrayLikeObject'),\n isBuffer = require('./isBuffer'),\n isFunction = require('./isFunction'),\n isObject = require('./isObject'),\n isPlainObject = require('./isPlainObject'),\n isTypedArray = require('./isTypedArray'),\n safeGet = require('./_safeGet'),\n toPlainObject = require('./toPlainObject');\n\n/**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n}\n\nmodule.exports = baseMergeDeep;\n","var Stack = require('./_Stack'),\n assignMergeValue = require('./_assignMergeValue'),\n baseFor = require('./_baseFor'),\n baseMergeDeep = require('./_baseMergeDeep'),\n isObject = require('./isObject'),\n keysIn = require('./keysIn'),\n safeGet = require('./_safeGet');\n\n/**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n}\n\nmodule.exports = baseMerge;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nmodule.exports = identity;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nmodule.exports = apply;\n","var apply = require('./_apply');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\nfunction overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n}\n\nmodule.exports = overRest;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nmodule.exports = constant;\n","var constant = require('./constant'),\n defineProperty = require('./_defineProperty'),\n identity = require('./identity');\n\n/**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n};\n\nmodule.exports = baseSetToString;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nmodule.exports = shortOut;\n","var baseSetToString = require('./_baseSetToString'),\n shortOut = require('./_shortOut');\n\n/**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar setToString = shortOut(baseSetToString);\n\nmodule.exports = setToString;\n","var identity = require('./identity'),\n overRest = require('./_overRest'),\n setToString = require('./_setToString');\n\n/**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\nfunction baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n}\n\nmodule.exports = baseRest;\n","var eq = require('./eq'),\n isArrayLike = require('./isArrayLike'),\n isIndex = require('./_isIndex'),\n isObject = require('./isObject');\n\n/**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\nfunction isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n}\n\nmodule.exports = isIterateeCall;\n","var baseRest = require('./_baseRest'),\n isIterateeCall = require('./_isIterateeCall');\n\n/**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\nfunction createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n}\n\nmodule.exports = createAssigner;\n","var baseMerge = require('./_baseMerge'),\n createAssigner = require('./_createAssigner');\n\n/**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\nvar merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n});\n\nmodule.exports = merge;\n","import merge from \"lodash/merge\";\nexport class GuideSettings {\n presentation;\n is_dismissible;\n opener_type;\n suspend_mode_settings;\n opener_settings;\n selector_timeout_settings;\n language;\n fillers;\n should_auto_play_first_step;\n tour_expiration_timeout;\n flow_flexibility;\n static DEFAULT_SETTINGS = {\n presentation: \"click_tour\",\n is_dismissible: false,\n opener_type: \"none\",\n language: {\n code: \"en\",\n name: \"English\",\n },\n suspend_mode_settings: {\n is_enabled: true,\n timeout: 45000,\n },\n selector_timeout_settings: {\n exist_timeout: 3000,\n not_exist_timeout: 3000,\n },\n fillers: {\n resumeTour: {\n title: \"I am taking you back\",\n content: \"Alright, let's jump back in!\",\n },\n targetLost: {\n title: \"Would you like to come back to the demo?\",\n resumeTourButtonText: \"Bring me back\",\n laterButtonText: \"Later\",\n avatarScript: \"Let me know once you’re ready to come back to the demo.\",\n },\n targetNotFound: {\n title: \"Sorry, there was an error. Can I assist you in any other way?\",\n restartButtonText: \"Restart the guide\",\n contactSupportButtonText: \"Contact support\",\n avatarScript: \"Sorry, there was an error. Can I assist you in any other way?\",\n },\n },\n should_auto_play_first_step: true,\n tour_expiration_timeout: 60,\n flow_flexibility: \"flexible\",\n };\n constructor(settings) {\n this.presentation = settings?.presentation ?? GuideSettings.DEFAULT_SETTINGS.presentation;\n this.is_dismissible = settings?.is_dismissible ?? GuideSettings.DEFAULT_SETTINGS.is_dismissible;\n this.opener_type = settings?.opener_type ?? GuideSettings.DEFAULT_SETTINGS.opener_type;\n this.opener_settings = settings?.opener_settings;\n this.language = settings?.language ?? GuideSettings.DEFAULT_SETTINGS.language;\n this.tour_expiration_timeout =\n settings?.tour_expiration_timeout ?? GuideSettings.DEFAULT_SETTINGS.tour_expiration_timeout;\n this.suspend_mode_settings = merge({}, GuideSettings.DEFAULT_SETTINGS.suspend_mode_settings, settings?.suspend_mode_settings);\n this.selector_timeout_settings = merge({}, GuideSettings.DEFAULT_SETTINGS.selector_timeout_settings, settings?.selector_timeout_settings);\n this.fillers = merge({}, GuideSettings.DEFAULT_SETTINGS.fillers, settings?.fillers);\n this.should_auto_play_first_step =\n settings?.should_auto_play_first_step ?? GuideSettings.DEFAULT_SETTINGS.should_auto_play_first_step;\n this.flow_flexibility = settings?.flow_flexibility ?? GuideSettings.DEFAULT_SETTINGS.flow_flexibility;\n }\n}\nexport class Guide {\n id;\n organization_id;\n title;\n description;\n created_at;\n updated_at;\n processed_at;\n targeting;\n settings;\n published_at;\n version;\n tour_playback;\n tour_playback_draft;\n avatar_id;\n editor_draft;\n archived_at;\n recording_activated_at;\n recording_session_id;\n processing_failed_at;\n processing_failure_details;\n recording_metadata;\n constructor(guide) {\n this.id = guide.id;\n this.organization_id = guide.organization_id;\n this.title = guide.title;\n this.description = guide.description;\n this.created_at = guide.created_at;\n this.updated_at = guide.updated_at;\n this.processed_at = guide.processed_at;\n this.targeting = guide.targeting;\n this.published_at = guide.published_at;\n this.settings = new GuideSettings(guide.settings);\n this.version = guide.version;\n this.tour_playback = guide.tour_playback;\n this.tour_playback_draft = guide.tour_playback_draft;\n this.avatar_id = guide.avatar_id;\n this.editor_draft = guide.editor_draft;\n this.archived_at = guide.archived_at;\n this.recording_activated_at = guide.recording_activated_at;\n this.recording_session_id = guide.recording_session_id;\n this.processing_failed_at = guide.processing_failed_at;\n this.processing_failure_details = guide.processing_failure_details;\n this.recording_metadata = guide.recording_metadata;\n }\n get isAIGuide() {\n return !!this.recording_activated_at;\n }\n get isPublished() {\n return !!this.published_at && new Date(this.published_at) <= new Date();\n }\n get isArchived() {\n return !!this.archived_at;\n }\n get isProcessing() {\n return !this.processed_at;\n }\n get status() {\n if (this.isPublished) {\n return \"published\";\n }\n if (this.isArchived) {\n return \"archived\";\n }\n return \"draft\";\n }\n}\n","import { Guide } from \"@common/models\";\nimport { TourState } from \"./persistent-storage/tourState\";\nimport { GuideScheduleReason } from \"./guideScheduler\";\n\nexport type GuideSchedulerEvents = {\n guideScheduled: { guide: Guide; scheduleReason: GuideScheduleReason; tourState?: TourState };\n guidesSynced: { guides: Guide[] };\n userTargeted: { guide: Guide };\n};\n\nexport const GuideSchedulerNamespace = \"guideScheduler\" as const;\n","import { reaction, toJS } from \"mobx\";\nimport { log } from \"@/lib/log\";\nimport { Guide } from \"@common/models\";\nimport { RawGuide } from \"@common/api/ping\";\nimport { PersistentStorage } from \"./persistent-storage/storage\";\nimport { EventEmitter } from \"../events/eventEmitter\";\nimport { GuideSchedulerEvents, GuideSchedulerNamespace } from \"./guideScheduler.events\";\nimport { GuideEvaluationResultWithOrder } from \"@/stores/GuideTargetingEvaluator\";\nimport { SyncResult } from \"../SyncManager\";\nimport { TourSessionManager } from \"./tourSessionManager\";\nimport { TourState } from \"./persistent-storage/tourState\";\n\nexport interface GuideSchedulerOptions {\n previewGuideId?: string;\n sharedGuideId?: string;\n}\n\ninterface GuideTargetingEvaluator {\n firstMatchingGuideId: string | null;\n evaluatedGuides: GuideEvaluationResultWithOrder[];\n}\n\ninterface GuideRegistry {\n findById(guideId: string): RawGuide | undefined;\n}\n\ninterface PyneClient {\n currentUser: { id: string; traits: Record } | null;\n}\n\ninterface SyncManager {\n syncGuides(params: {\n previewGuideId?: string;\n activeGuideId?: string;\n tourPlaybackVersion?: string;\n }): Promise;\n}\n\ninterface GuideSchedulerParams {\n options?: GuideSchedulerOptions;\n guideTargetingEvaluator: GuideTargetingEvaluator;\n guideRegistry: GuideRegistry;\n pyneClient: PyneClient;\n syncManager: SyncManager;\n storage: PersistentStorage;\n tourSessionManager: TourSessionManager;\n}\n\nexport type PreparedGuide = {\n guideId: string;\n stepId?: string;\n preparedFor: \"preview\" | \"shared\";\n};\n\nexport type GuideScheduleReason =\n | \"user_targeted\"\n | \"preview\"\n | \"shared\"\n | \"tour_session_recovered\"\n | \"trigger_from_pyne_client\"\n | \"trigger_from_other_tour\"\n | \"trigger_from_debugger\";\n\nexport class GuideScheduler {\n private currentGuide?: Guide;\n private options?: GuideSchedulerOptions;\n private isInitialized = false;\n private status: \"initialized\" | \"started\" | \"resyncing\" | \"synced\" | \"stopped\" = \"initialized\";\n private guideTargetingEvaluator: GuideTargetingEvaluator;\n private pyneClient: PyneClient;\n private syncManager: SyncManager;\n private storage: PersistentStorage;\n private tourSessionManager: TourSessionManager;\n private guideRegistry: GuideRegistry;\n events = new EventEmitter(GuideSchedulerNamespace);\n\n static readonly initialSyncGuidesDelay = 50;\n static readonly syncGuidesInterval = 1000;\n static readonly scheduleGuideInterval = 1000;\n\n constructor({\n guideTargetingEvaluator,\n pyneClient,\n syncManager,\n guideRegistry,\n storage,\n tourSessionManager,\n options,\n }: GuideSchedulerParams) {\n this.guideTargetingEvaluator = guideTargetingEvaluator;\n this.pyneClient = pyneClient;\n this.syncManager = syncManager;\n this.guideRegistry = guideRegistry;\n this.storage = storage;\n this.options = options;\n this.tourSessionManager = tourSessionManager;\n }\n\n start() {\n if (this.isInitialized && this.status === \"stopped\") {\n this.status = \"synced\";\n }\n\n if (this.isInitialized) {\n return;\n }\n\n if (this.previewGuideId) {\n this.startPreviewSession();\n }\n\n if (this.sharedGuideId) {\n this.startSharedSession();\n }\n\n log(\"Guide scheduler starting\");\n\n this.status = \"started\";\n if (!this.isInitialized) {\n this.initGuideSync();\n this.initPeriodicGuidePicker();\n this.isInitialized = true;\n }\n }\n\n stop() {\n this.status = \"stopped\";\n this.clearCurrentGuide();\n }\n\n switchGuide(guideId: string, reason: \"trigger_from_pyne_client\" | \"trigger_from_other_tour\") {\n this.startGuideById(guideId, reason);\n }\n\n clearCurrentGuide() {\n this.currentGuide = undefined;\n }\n\n private initGuideSync() {\n log(\"Guide sync initializing\");\n // Run when event loop is free\n setTimeout(async () => {\n log(\"will sync guides\");\n await this.syncGuides();\n }, GuideScheduler.initialSyncGuidesDelay);\n\n setInterval(async () => {\n if (this.status === \"synced\" && this.isUserStateRemoved()) {\n this.status = \"resyncing\";\n await this.syncGuides();\n }\n }, GuideScheduler.syncGuidesInterval);\n\n // Run when user is identified\n reaction(\n () => this.pyneClient.currentUser,\n async () => {\n await this.syncGuides();\n }\n );\n }\n\n private initPeriodicGuidePicker() {\n log(\"periodic guide picker initialized\");\n\n const schedule = () => {\n log(\"scheduling...\", !this.currentGuide, this.status, this.isAlreadyInSync());\n if (!this.currentGuide && this.isAlreadyInSync()) {\n log(\"trying to schedule guide\");\n this.scheduleGuide();\n }\n };\n\n setInterval(() => {\n schedule();\n }, GuideScheduler.scheduleGuideInterval);\n }\n\n private isUserStateRemoved() {\n return this.status === \"synced\" && !this.storage.userState.isExists();\n }\n\n private isAlreadyInSync() {\n return this.status === \"synced\" && this.storage.userState.isExists();\n }\n\n private async syncGuides() {\n log(\"syncing guides\");\n\n const tourSessionToRecover = this.tourSessionManager.getRecoverableTourSession();\n const syncResult = await this.syncManager.syncGuides({\n previewGuideId: this.previewGuideId,\n activeGuideId: tourSessionToRecover?.activeTourGuideId,\n tourPlaybackVersion: tourSessionToRecover?.tourPlaybackVersion,\n });\n\n if (!syncResult) {\n return;\n }\n\n this.storage.userState.hydrate(syncResult.userState);\n\n this.status = \"synced\";\n log(\"syncResult\", syncResult, this.status);\n }\n\n preparedGuide?: PreparedGuide;\n\n private prepareTourForScheduling(preparedGuide: PreparedGuide) {\n this.preparedGuide = preparedGuide;\n }\n\n private clearPreparedGuide() {\n this.preparedGuide = undefined;\n }\n\n private startPreviewSession() {\n if (!this.previewGuideId) {\n return;\n }\n\n log(\"starting preview session\", this.previewGuideId);\n this.prepareTourForScheduling({ guideId: this.previewGuideId, preparedFor: \"preview\" });\n }\n\n private startSharedSession() {\n if (!this.sharedGuideId) {\n return;\n }\n\n this.prepareTourForScheduling({ guideId: this.sharedGuideId, preparedFor: \"shared\" });\n }\n\n private scheduleGuide() {\n if (!this.guideTargetingEvaluator.evaluatedGuides.length) {\n return;\n }\n\n const tourStateToRecover = this.tourSessionManager.getRecoverableTourSession();\n\n if (this.preparedGuide) {\n this.startGuideById(this.preparedGuide.guideId, this.preparedGuide.preparedFor, tourStateToRecover);\n this.clearPreparedGuide();\n return true;\n }\n\n // Start if there is a recoverable tour session\n if (tourStateToRecover) {\n this.startGuideById(tourStateToRecover.activeTourGuideId!, \"tour_session_recovered\", tourStateToRecover);\n return true;\n }\n\n // Do not search for other guides if we are in preview mode\n if (this.isPreviewEnabled()) {\n log(\"preview mode, not scheduling guide\");\n return false;\n }\n\n const guideId = this.guideTargetingEvaluator.firstMatchingGuideId;\n if (guideId) {\n const guide = this.guideRegistry.findById(guideId);\n if (!guide) return false;\n\n log(\"starting first matching guide\", toJS(guide));\n const guideModel = new Guide(guide);\n this.startGuide(guideModel, \"user_targeted\");\n\n return true;\n }\n\n log(\"no guide found\");\n return false;\n }\n\n private startGuideById(guideId: string, scheduleReason: GuideScheduleReason, tourState?: TourState) {\n const guide = this.guideRegistry.findById(guideId);\n\n if (guide) {\n const guideModel = new Guide(guide);\n this.startGuide(guideModel, scheduleReason, tourState);\n return true;\n }\n\n return false;\n }\n\n private startGuide(guide: Guide, scheduleReason: GuideScheduleReason, tourState?: TourState) {\n log(\"starting guide\", guide.id, guide.title);\n if (scheduleReason === \"user_targeted\") {\n this.events.emit(\"userTargeted\", { guide });\n }\n this.currentGuide = guide;\n this.events.emit(\"guideScheduled\", { guide, scheduleReason, tourState });\n }\n\n private isPreviewEnabled() {\n return !!this.options?.previewGuideId;\n }\n\n private get previewGuideId() {\n return this.options?.previewGuideId;\n }\n\n private get sharedGuideId() {\n return this.options?.sharedGuideId;\n }\n}\n","import { StorageHandler, sendStorageEvent } from \"@/lib/storage\";\nimport { getWindow } from \"@/lib/window\";\nimport { isEqual } from \"lodash-es\";\n\nexport interface TabState {\n tabs?: string[];\n activeTabId?: string;\n}\n\nexport type TabStateStorage = ReturnType;\n\nconst storageKey = (suffix?: boolean) => `pyne-tab-state${suffix ? \"preview\" : \"\"}`;\nconst currentTabIdKey = \"pyne-current-tab-id\";\n\nexport const buildTabStateStorage = (suffix: boolean, storage: StorageHandler, sessionStorage: StorageHandler) => {\n const self = () => buildTabStateStorage(suffix, storage, sessionStorage);\n\n return {\n key: () => {\n return storageKey(suffix);\n },\n get: () => {\n return storage.get(storageKey(suffix), {});\n },\n clear: () => {\n storage.remove(storageKey(suffix));\n },\n set: (state: Partial) => {\n storage.set(storageKey(suffix), { ...self().get(), ...state });\n },\n addTab: (tabId: string) => {\n self().set({\n tabs: [...self().getTabs(), tabId],\n });\n },\n setCurrentTabId: (tabId: string) => {\n sessionStorage.set(currentTabIdKey, tabId);\n },\n setActiveTab: (tabId?: string) => {\n const oldValue = self().get();\n self().set({ activeTabId: tabId });\n const newValue = self().get();\n sendStorageEvent(storageKey(suffix), JSON.stringify(oldValue), JSON.stringify(newValue));\n },\n clearActiveTab: () => {\n const oldValue = self().get();\n self().set({ activeTabId: undefined });\n const newValue = self().get();\n sendStorageEvent(storageKey(suffix), JSON.stringify(oldValue), JSON.stringify(newValue));\n },\n clearTab: (tabId: string) => {\n const oldValue = self().get();\n self().removeTab(tabId);\n self().set({ activeTabId: undefined });\n const newValue = self().get();\n sendStorageEvent(storageKey(suffix), JSON.stringify(oldValue), JSON.stringify(newValue));\n },\n removeTab: (tabId: string) => {\n self().set({\n tabs: self()\n .getTabs()\n .filter((id) => id !== tabId),\n });\n },\n getCurrentTabId: (): string | undefined => {\n return sessionStorage.get(currentTabIdKey, undefined);\n },\n getActiveTabId: (): string | undefined => {\n return self().get().activeTabId;\n },\n getTabs: (): string[] => {\n return self().get().tabs || [];\n },\n onActiveTabChange: (callback: (activeTabId?: string) => void) => {\n let lastActiveTabId: string | undefined = self().get().activeTabId;\n\n const activeTabChangedCallback = () => {\n const activeTabId = self().get().activeTabId;\n if (activeTabId !== lastActiveTabId) {\n lastActiveTabId = activeTabId;\n callback(activeTabId);\n }\n };\n\n const storageListener = (event: StorageEvent) => {\n if (event.key === storageKey(suffix)) {\n const oldState = JSON.parse(event.oldValue ?? \"{}\");\n const newState = JSON.parse(event.newValue ?? \"{}\");\n\n if (oldState.activeTabId !== newState.activeTabId) {\n activeTabChangedCallback();\n }\n }\n };\n\n getWindow().addEventListener(\"storage\", storageListener);\n getWindow().addEventListener(\"unload\", () => {\n getWindow().removeEventListener(\"storage\", storageListener);\n });\n },\n onTabsChange: (callback: (tabs: string[]) => void) => {\n let lastTabs: string[] = [];\n\n const updateTabs = () => {\n const tabs = self().getTabs();\n if (!isEqual(tabs, lastTabs)) {\n lastTabs = tabs;\n callback(tabs);\n }\n };\n\n updateTabs();\n\n const storageListener = (event: StorageEvent) => {\n if (event.key === storageKey(suffix)) {\n const oldState = JSON.parse(event.oldValue ?? \"{}\");\n const newState = JSON.parse(event.newValue ?? \"{}\");\n\n if (!isEqual(oldState.tabs, newState.tabs)) {\n updateTabs();\n }\n }\n };\n\n getWindow().addEventListener(\"storage\", storageListener);\n getWindow().addEventListener(\"unload\", () => {\n getWindow().removeEventListener(\"storage\", storageListener);\n });\n },\n };\n};\n","import { StorageHandler } from \"@/lib/storage\";\nimport { uuid } from \"@/lib/utils\";\n\nexport interface PreviewState {\n isEnabled: boolean;\n sessionId?: string;\n}\n\nexport type PreviewStateStorage = ReturnType;\n\nconst key = \"pyne-preview-state\";\n\nexport const buildPreviewStateStorage = (storage: StorageHandler) => {\n const self = () => buildPreviewStateStorage(storage);\n\n return {\n get: () => {\n return storage.get(key, { isEnabled: false });\n },\n isPreview: () => {\n return self().get().isEnabled;\n },\n enable: (guideId: string) => {\n storage.set(key, { isEnabled: true, sessionId: uuid(), guideId, initialUrl: location.href });\n },\n getSessionId: () => {\n return self().get().sessionId;\n },\n getGuideId: () => {\n return self().get().guideId;\n },\n clear: () => {\n storage.remove(key);\n },\n };\n};\n","import { StorageHandler } from \"@/lib/storage\";\nimport { makeAutoObservable } from \"mobx\";\n\nexport interface SessionState {\n visitedAtUnix?: number;\n expiredTourGuideIds?: string[];\n}\n\nexport class SessionStateStorage {\n private isPreview: boolean;\n private storage: StorageHandler;\n private _state: SessionState;\n\n constructor(isPreview: boolean, storage: StorageHandler) {\n this.isPreview = isPreview;\n this.storage = storage;\n this._state = this.get();\n makeAutoObservable(this);\n }\n\n private storageKey(): string {\n return `pyne-session-state${this.isPreview ? \"-preview\" : \"\"}`;\n }\n\n public isExists(): boolean {\n return this.storage.isKeyExists(this.storageKey());\n }\n\n public get(): SessionState {\n return this.storage.get(this.storageKey(), {});\n }\n\n public clear(): void {\n this.storage.remove(this.storageKey());\n this._state = {};\n }\n\n public set(state: Partial): void {\n this._state = { ...this._state, ...state };\n this.storage.set(this.storageKey(), this._state);\n }\n\n public setVisitedAt(): number {\n const date = Date.now();\n const visitedAtUnix = this.get().visitedAtUnix;\n if (!visitedAtUnix) {\n this.set({ visitedAtUnix: date });\n return date;\n }\n return visitedAtUnix;\n }\n\n public getVisitedAt(): number {\n const visitedAtUnix = this.get().visitedAtUnix;\n return visitedAtUnix ? visitedAtUnix : this.setVisitedAt();\n }\n\n get expiredTourGuideIds(): string[] {\n return this._state.expiredTourGuideIds ?? [];\n }\n\n public addExpiredGuide(guideId: string): void {\n const expiredTourGuideIds = this._state.expiredTourGuideIds ?? [];\n this._state.expiredTourGuideIds = [...expiredTourGuideIds, guideId];\n this.storage.set(this.storageKey(), this._state);\n }\n}\n","import { StorageHandler } from \"@/lib/storage\";\nimport { makeAutoObservable, runInAction } from \"mobx\";\n\nexport interface DebuggerState {\n isEnabled: boolean;\n isMinimized: boolean;\n isDevModeEnabled: boolean;\n isAdvancedDetailsEnabled: boolean;\n isTourDetailsOpenedFromGuideList: boolean;\n isGuideListModalVisible: boolean;\n isTourDetailsModalVisible: boolean;\n isUserDataModalVisible: boolean;\n isReportBugModalVisible: boolean;\n isStateDataModalVisible: boolean;\n selectedGuideId?: string;\n selectedStepId?: string;\n advancedDetailsTab: string;\n capturedEvents?: any[];\n}\n\nexport class DebuggerStateStorage {\n private storage: StorageHandler;\n private _state: DebuggerState;\n\n constructor(storage: StorageHandler) {\n this.storage = storage;\n this._state = this.get();\n makeAutoObservable(this);\n }\n\n private storageKey(): string {\n return \"pyne-debugger-state\";\n }\n\n get isEnabled(): boolean {\n return this._state.isEnabled;\n }\n\n get isMinimized(): boolean {\n return this._state.isMinimized;\n }\n\n get isAdvancedDetailsEnabled(): boolean {\n return this._state.isAdvancedDetailsEnabled;\n }\n\n get isTourDetailsOpenedFromGuideList(): boolean {\n return this._state.isTourDetailsOpenedFromGuideList;\n }\n\n get isGuideListModalVisible(): boolean {\n return this._state.isGuideListModalVisible;\n }\n\n get isTourDetailsModalVisible(): boolean {\n return this._state.isTourDetailsModalVisible;\n }\n\n get isUserDataModalVisible(): boolean {\n return this._state.isUserDataModalVisible;\n }\n\n get isReportBugModalVisible(): boolean {\n return this._state.isReportBugModalVisible;\n }\n\n get selectedGuideId(): string | undefined {\n return this._state.selectedGuideId;\n }\n\n get selectedStepId(): string | undefined {\n return this._state.selectedStepId;\n }\n\n get advancedDetailsTab(): string {\n return this._state.advancedDetailsTab;\n }\n\n get capturedEventsLength() {\n return this._state.capturedEvents?.length;\n }\n\n public get(): DebuggerState {\n return this.storage.get(this.storageKey(), {\n isEnabled: false,\n isMinimized: true,\n isAdvancedDetailsEnabled: false,\n isTourDetailsOpenedFromGuideList: false,\n isGuideListModalVisible: false,\n isTourDetailsModalVisible: false,\n isUserDataModalVisible: false,\n isReportBugModalVisible: false,\n isStateDataModalVisible: false,\n advancedDetailsTab: \"targeting\",\n capturedEvents: [],\n });\n }\n\n public clear(): void {\n this.storage.remove(this.storageKey());\n this._state = this.get();\n }\n\n public set(state: Partial): void {\n runInAction(() => {\n this._state = { ...this._state, ...state };\n this.storage.set(this.storageKey(), this._state);\n });\n }\n\n public setCapturedEvents(events: any[]): void {\n this.set({ capturedEvents: events.slice(-500) });\n }\n\n public clearCapturedEvents(): void {\n this.set({ capturedEvents: [] });\n }\n\n public enable(): void {\n this.set({ isEnabled: true });\n }\n\n public disable(): void {\n this.set({ isEnabled: false });\n }\n}\n","import { StorageHandler } from \"@/lib/storage\";\nimport { AvatarStateStorage, buildAvatarStateStorage } from \"./avatarState\";\nimport { TabStateStorage, buildTabStateStorage } from \"./tabState\";\nimport { TourStateStorage, buildTourStateStorage } from \"./tourState\";\nimport { UserStateStorage } from \"./userState\";\nimport { PreviewStateStorage, buildPreviewStateStorage } from \"./previewState\";\nimport { SessionStateStorage } from \"./sessionState\";\nimport { DebuggerStateStorage } from \"./debuggerState\";\n\nexport interface PersistentStorageParams {\n localStorageHandler: StorageHandler;\n sessionStorageHandler: StorageHandler;\n}\n\nexport class PersistentStorage {\n private isPreview = false;\n\n userState!: UserStateStorage;\n tourState!: TourStateStorage;\n tabState!: TabStateStorage;\n sessionState!: SessionStateStorage;\n avatarState!: AvatarStateStorage;\n debuggerState: DebuggerStateStorage;\n previewState: PreviewStateStorage;\n\n private explicitPreviewState?: {\n userState: UserStateStorage;\n tourState: TourStateStorage;\n tabState: TabStateStorage;\n avatarState: AvatarStateStorage;\n };\n\n private localStorageHandler: StorageHandler;\n private sessionStorageHandler: StorageHandler;\n\n constructor({ localStorageHandler, sessionStorageHandler }: PersistentStorageParams) {\n this.previewState = buildPreviewStateStorage(sessionStorageHandler);\n this.debuggerState = new DebuggerStateStorage(localStorageHandler);\n this.localStorageHandler = localStorageHandler;\n this.sessionStorageHandler = sessionStorageHandler;\n this.sessionState = new SessionStateStorage(this.isPreview, this.sessionStorageHandler);\n\n // Preview mode is disabled by default\n this.initializeStateStorages(this.isPreview);\n if (this.isPreview) {\n this.initializeNonPreviewStateStorages();\n }\n }\n\n enablePreviewMode() {\n this.isPreview = true;\n this.initializeStateStorages(this.isPreview);\n }\n\n private initializeStateStorages(isPreview: boolean) {\n const { userState, tourState, tabState, avatarState } = this.createStateStorages(isPreview);\n this.userState = userState;\n this.tourState = tourState;\n this.tabState = tabState;\n this.avatarState = avatarState;\n }\n\n private initializeNonPreviewStateStorages() {\n const { userState, tourState, tabState, avatarState } = this.createStateStorages(false);\n this.explicitPreviewState = {\n userState,\n tourState,\n tabState,\n avatarState,\n };\n }\n\n private createStateStorages(isPreview: boolean) {\n return {\n userState: new UserStateStorage(isPreview, this.localStorageHandler),\n tourState: buildTourStateStorage(isPreview, this.localStorageHandler),\n tabState: buildTabStateStorage(isPreview, this.localStorageHandler, this.sessionStorageHandler),\n avatarState: buildAvatarStateStorage(isPreview, this.localStorageHandler),\n };\n }\n\n clearTourRelatedState() {\n this.tourState.clear();\n this.tabState.clear();\n this.avatarState.clear();\n this.userState.clear();\n if (this.explicitPreviewState) {\n this.explicitPreviewState.tourState.clear();\n this.explicitPreviewState.tabState.clear();\n this.explicitPreviewState.avatarState.clear();\n this.explicitPreviewState.userState.clear();\n }\n }\n\n clearTourState() {\n this.tourState.clear();\n if (this.explicitPreviewState) {\n this.explicitPreviewState.tourState.clear();\n }\n }\n\n clearAll() {\n this.userState.clear();\n this.tourState.clear();\n this.tabState.clear();\n this.avatarState.clear();\n this.previewState.clear();\n\n if (this.explicitPreviewState) {\n this.explicitPreviewState.userState.clear();\n this.explicitPreviewState.tourState.clear();\n this.explicitPreviewState.tabState.clear();\n this.explicitPreviewState.avatarState.clear();\n }\n }\n}\n","import { CSSProperties } from \"react\";\nimport { makeAutoObservable, runInAction } from \"mobx\";\nimport { store, type RootStore } from \"@/store\";\n\nconst primaryButton: number = 0;\nconst sloppyClickThreshold: number = 5;\n\nconst calcAvatarSize = () => {\n return Math.floor(Math.max(window.innerWidth * 0.15, 120));\n};\n\nexport class AvatarPositioner {\n avatarWidth = calcAvatarSize();\n\n avatarEl: HTMLElement | null = null;\n\n mouseX = 0;\n mouseY = 0;\n\n customAvatarPosition: null | { x: number; y: number } = null;\n isPositionedRight = false;\n\n dragging: null | {\n // state:\n // \"pending\" means the the avatar was clicked, but we don't know if the user is dragging or not\n // \"dragging\" means the user is dragging the avatar\n state: \"pending\" | \"dragging\";\n\n mouseX0: number;\n mouseY0: number;\n\n avatarX0: number;\n avatarY0: number;\n } = null;\n\n constructor(public rootStore: RootStore) {\n makeAutoObservable(this);\n\n const updateAvatarSize = () => {\n this.avatarWidth = calcAvatarSize();\n };\n\n window.addEventListener(\"resize\", updateAvatarSize);\n\n this.loadCustomPosition();\n }\n\n resetPosition() {\n this.customAvatarPosition = null;\n }\n\n loadCustomPosition() {\n const storedPosition = sessionStorage.getItem(\"pyne-avatar-position\");\n if (storedPosition) {\n const position = JSON.parse(storedPosition);\n\n runInAction(() => {\n this.customAvatarPosition = position;\n });\n }\n }\n\n saveCustomPosition() {\n if (this.customAvatarPosition) {\n sessionStorage.setItem(\"pyne-avatar-position\", JSON.stringify(this.customAvatarPosition));\n } else {\n sessionStorage.removeItem(\"pyne-avatar-position\");\n }\n }\n\n get avatarBottomOffset() {\n if (store.pyneSettings.debug) {\n return 44;\n }\n\n return 20;\n }\n\n get avatarPosition(): { x: number; y: number; cssPostion: CSSProperties; snapped?: boolean } {\n const defaultPosition = {\n x: 20,\n y: window.innerHeight - this.avatarBottomOffset - this.avatarWidth,\n cssPostion: { left: 20, bottom: this.avatarBottomOffset },\n };\n\n if (this.customAvatarPosition) {\n const snapThreshold = 20;\n const dist = Math.sqrt(\n (this.customAvatarPosition?.x - defaultPosition.x) ** 2 +\n (this.customAvatarPosition?.y - defaultPosition.y) ** 2\n );\n\n if (dist <= snapThreshold) {\n return { ...defaultPosition, snapped: true };\n }\n\n return {\n x: this.customAvatarPosition.x,\n y: this.customAvatarPosition.y,\n cssPostion: { top: this.customAvatarPosition.y, left: this.customAvatarPosition.x },\n };\n }\n if (this.isPositionedRight) {\n return {\n x: window.innerWidth - 20 - this.avatarWidth,\n y: window.innerHeight - this.avatarBottomOffset - this.avatarWidth,\n cssPostion: { right: 20, bottom: this.avatarBottomOffset },\n };\n }\n\n return defaultPosition;\n }\n\n get isDragging() {\n return this.dragging?.state === \"dragging\";\n }\n\n updateElement(el: HTMLElement | null) {\n if (this.avatarEl && this.avatarEl !== el) {\n // unregister old element\n this.avatarEl?.removeEventListener(\"mousedown\", this.handleMouseDown);\n window.removeEventListener(\"click\", this.handleMouseUp, { capture: true });\n window.removeEventListener(\"mousemove\", this.handleMouseMove);\n this.avatarEl = null;\n }\n\n if (el && this.avatarEl !== el) {\n // register new element\n el.addEventListener(\"mousedown\", this.handleMouseDown);\n window.addEventListener(\"click\", this.handleMouseUp, { capture: true });\n window.addEventListener(\"mousemove\", this.handleMouseMove);\n this.avatarEl = el;\n }\n }\n\n handleMouseDown = (e: MouseEvent) => {\n if (e.button !== primaryButton) return;\n\n this.mouseX = e.clientX;\n this.mouseY = e.clientY;\n this.dragging = {\n state: \"pending\",\n mouseX0: e.clientX,\n mouseY0: e.clientY,\n avatarX0: this.avatarPosition.x,\n avatarY0: this.avatarPosition.y,\n };\n };\n\n handleMouseMove = (e: MouseEvent) => {\n if (!this.dragging) return;\n\n this.mouseX = e.clientX;\n this.mouseY = e.clientY;\n\n const isSloppyClick =\n (!this.isDragging && Math.abs(this.dragging.mouseX0 - this.mouseX) <= sloppyClickThreshold) ||\n Math.abs(this.dragging.mouseY0 - this.mouseY) <= sloppyClickThreshold;\n if (isSloppyClick) return;\n\n if (!this.isDragging) {\n // drag started\n this.dragging.state = \"dragging\";\n }\n\n this.updateAvatarPosition();\n };\n\n handleMouseUp = (e: MouseEvent) => {\n if (this.dragging?.state === \"dragging\") {\n e.preventDefault();\n e.stopPropagation();\n\n if (this.avatarPosition.snapped) {\n this.resetPosition();\n }\n\n this.saveCustomPosition();\n }\n\n this.dragging = null;\n };\n\n updateAvatarPosition() {\n const avatarX = this.isDragging\n ? this.dragging!.avatarX0 + (this.mouseX - this.dragging!.mouseX0)\n : this.avatarPosition.x;\n const avatarY = this.isDragging\n ? this.dragging!.avatarY0 + (this.mouseY - this.dragging!.mouseY0)\n : this.avatarPosition.y;\n this.customAvatarPosition = { x: avatarX, y: avatarY };\n }\n\n get stylesheetContent() {\n let content = \"\";\n\n if (this.isDragging) {\n content += /* css */ `\n * {\n cursor: grabbing !important;\n user-select: none !important;\n }\n `;\n }\n\n content += /* css */ `\n #pyne-avatar, #pyne-avatar-skeleton {\n /* unset old avatar styles */\n bottom: unset;\n left: unset;\n width: unset;\n padding-bottom: unset;\n height: unset;\n\n position: fixed;\n --pyne-avatar-size: ${this.avatarWidth}px;\n ${this.avatarWidth === 0 ? \"display: none;\" : \"\"}\n width: ${this.avatarWidth}px;\n height: ${this.avatarWidth}px;\n ${Object.entries(this.avatarPosition.cssPostion)\n .map(([key, value]) => `${key}: ${value}px;`)\n .join(\"\\n\")}\n }\n `;\n return content;\n }\n}\n","import { TourPlayback } from \"@common/schemas\";\nimport { getUrl, isUrlEqualsToCurrentUrl } from \"../window\";\nimport { waitForOnTrackConditions } from \"./onTrackConditionCheck\";\nimport * as models from \"@common/models/v2\";\nimport { TourState } from \"./persistent-storage/tourState\";\nimport { SuspendReason } from \"./tourPlayback/types\";\nimport { findLastCheckpoint } from \"./checkpoint\";\n\nexport type TourStartStrategyType = \"startOver\" | \"resume\" | \"bringBack\" | \"startSuspended\";\n\nexport type BaseTourStartStrategy = {\n type: TourStartStrategyType;\n description?: string;\n message?: string;\n};\n\nexport type StartOverStrategy = BaseTourStartStrategy & {\n type: \"startOver\";\n};\n\nexport type ResumeStrategy = BaseTourStartStrategy & {\n type: \"resume\";\n stepId: string;\n};\n\nexport type BringBackStrategy = BaseTourStartStrategy & {\n type: \"bringBack\";\n url: string;\n stepId: string;\n};\n\nexport type StartSuspendedStrategy = BaseTourStartStrategy & {\n type: \"startSuspended\";\n reason: SuspendReason;\n};\n\nexport type TourStartStrategy = StartOverStrategy | ResumeStrategy | BringBackStrategy | StartSuspendedStrategy;\n\nexport class TourStartManager {\n initialTourStateSnapshot?: TourState;\n\n async decideStrategy(tabId: string, tourPlayback: TourPlayback, tourState?: TourState): Promise {\n this.saveInitialTourStateSnapshot(tourState);\n\n const isActiveTourExists = this.isActiveTourExists(tourState);\n if (!isActiveTourExists) {\n return { type: \"startOver\", message: \"No active tour exists\" };\n }\n\n const isActiveTourSuspended = this.isActiveTourSuspended({ withReason: [\"userAction\"] }, tourState);\n if (isActiveTourSuspended) {\n return { type: \"startSuspended\", message: \"Active tour is suspended\", reason: \"userAction\" };\n }\n\n const isActiveTourPlayingOnOtherTab = this.isActiveTourPlayingOnOtherTab(tabId, tourState);\n if (isActiveTourPlayingOnOtherTab) {\n return {\n type: \"startSuspended\",\n message: \"Active tour is playing on other tab\",\n reason: \"tourPlayingOnOtherTab\",\n };\n }\n\n const activeStepId = tourState?.activeStepId;\n const lastCheckpoint = this.getLastCheckpoint(tourState);\n const lastCompletedStepId = tourState?.lastCompletedStepId;\n\n if (!lastCheckpoint || !activeStepId) {\n return { type: \"startOver\", message: \"No last checkpoint or active step\" };\n }\n\n const isUrlChanged = this.isLastPageUrlChanged(tourState);\n const isActiveStepEqualsLastCheckpointStep = lastCheckpoint.stepId === activeStepId;\n const shouldContinueFromNextStep = isActiveStepEqualsLastCheckpointStep || isUrlChanged;\n\n if (shouldContinueFromNextStep) {\n const nextStepId = this.getNextStepId(tourPlayback, lastCompletedStepId);\n if (!nextStepId) {\n // TODO: handle different\n return {\n type: \"startOver\",\n message: \"No next step after last completed step\",\n };\n }\n\n const isNextStepOnTrack = await this.isStepOnTrack(nextStepId, tourPlayback);\n if (isNextStepOnTrack) {\n return {\n type: \"resume\",\n stepId: nextStepId,\n description: \"Will continue from step after last completed step\",\n message: \"Handling full page reloads on page transitions\",\n };\n }\n }\n\n if (isUrlEqualsToCurrentUrl(lastCheckpoint.url)) {\n return {\n type: \"resume\",\n stepId: lastCheckpoint.stepId,\n description: \"Will continue from last checkpoint\",\n message: \"Last checkpoint is on the same page\",\n };\n }\n\n return {\n type: \"bringBack\",\n url: lastCheckpoint.url,\n stepId: lastCheckpoint.stepId,\n message: \"Last checkpoint is on a different page\",\n };\n }\n\n private isLastPageUrlChanged(tourState: TourState): boolean {\n const lastPageUrl = tourState.lastPageUrl;\n if (!lastPageUrl) {\n return false;\n }\n return !isUrlEqualsToCurrentUrl(lastPageUrl);\n }\n\n private getNextStepId(tourPlayback: TourPlayback, stepId?: string): string | undefined {\n if (!stepId) {\n return tourPlayback.sections[0].steps[0].id;\n }\n\n const steps = tourPlayback.sections.flatMap((section) => section.steps);\n const stepIndex = steps.findIndex((step) => step.id === stepId);\n\n const isStepNotFound = stepIndex === -1;\n const isLastStep = stepIndex === steps.length - 1;\n if (isStepNotFound || isLastStep) {\n return;\n }\n\n return steps[stepIndex + 1].id;\n }\n\n private async isStepOnTrack(stepId: string, tourPlayback: TourPlayback): Promise {\n const step = tourPlayback.sections.flatMap((section) => section.steps).find((step) => step.id === stepId);\n\n if (!step) {\n return false;\n }\n\n const stepModel = new models.Step(step);\n const url = getUrl();\n return await waitForOnTrackConditions(stepModel.attributes.onTrackConditions, url);\n }\n\n isActiveTourExists(tourState?: TourState): boolean {\n return !!tourState?.activeTourGuideId;\n }\n\n isActiveTourSuspended({ withReason }: { withReason: SuspendReason[] }, tourState?: TourState): boolean {\n if (!tourState?.activeTourGuideId) {\n return false;\n }\n\n if (!tourState.isSuspended || !tourState.suspendReason) {\n return false;\n }\n\n return tourState.isSuspended && withReason.map((r) => r.toString()).includes(tourState.suspendReason);\n }\n\n private isActiveTourPlayingOnOtherTab(tabId: string, tourState?: TourState) {\n if (!tourState?.activeTourGuideId) {\n return false;\n }\n\n return tourState.tabId !== tabId;\n }\n\n private saveInitialTourStateSnapshot(tourState?: TourState) {\n if (tourState) {\n this.initialTourStateSnapshot = tourState;\n return;\n }\n }\n\n private getLastCheckpoint(tourState?: TourState) {\n if (!tourState) {\n return null;\n }\n\n const checkpoints = tourState.checkpoints;\n if (!checkpoints) {\n return null;\n }\n\n return findLastCheckpoint(checkpoints);\n }\n}\n","import { EmptyPayload } from \"../events/types\";\n\nexport interface TabManagerEvents {\n activeTabChanged: { tabId?: string };\n tabsChanged: { tabs: string[] };\n otherTabTookoverTheTour: EmptyPayload;\n currentTabActivated: EmptyPayload;\n currentTabInactivated: EmptyPayload;\n otherTabActivated: EmptyPayload;\n allTabsInactive: EmptyPayload;\n}\n\nexport type TabManagerEventContext = {\n tabId: string;\n};\n\nexport const TabManagerNamespace = \"tabManager\" as const;\n","import { globalEventBus } from \"../events/eventBus\";\nimport { EventEmitter } from \"../events/eventEmitter\";\nimport { getWindow } from \"../window\";\nimport { TabStateStorage } from \"./persistent-storage/tabState\";\nimport { TourStateStorage } from \"./persistent-storage/tourState\";\nimport { TabManagerEvents, TabManagerNamespace } from \"./tabManager.events\";\n\nexport interface TabManagerParams {\n tabState: TabStateStorage;\n tourState: TourStateStorage;\n}\n\nexport class TabManager {\n tabState: TabStateStorage;\n tourState: TourStateStorage;\n tabId: string;\n events = new EventEmitter(TabManagerNamespace);\n\n constructor({ tabState, tourState }: TabManagerParams) {\n this.tabState = tabState;\n this.tourState = tourState;\n this.tabId = this.tabState.getCurrentTabId() ?? Date.now().toString();\n\n globalEventBus.use(\"*\", (context) => {\n return { ...context, tabId: this.tabId };\n });\n\n this.init();\n }\n\n amIActive() {\n return this.tabState.getActiveTabId() === this.tabId;\n }\n\n private init() {\n this.tabState.setCurrentTabId(this.tabId);\n this.tabState.addTab(this.tabId);\n this.tabState.setActiveTab(this.tabId);\n\n getWindow().document.addEventListener(\"visibilitychange\", () => this.handleTabVisibilityChange());\n getWindow().addEventListener(\"unload\", () => this.handleTabClose());\n\n this.listenActiveTabChange();\n this.listenTabsChange();\n this.listenActiveTourTabChange();\n }\n\n private listenActiveTabChange() {\n this.tabState.onActiveTabChange((tabId?: string) => {\n this.events.emit(\"activeTabChanged\", { tabId }, {}, { skipGlobal: true });\n\n if (!tabId) {\n this.events.emit(\"currentTabInactivated\", {}, {}, { skipGlobal: true });\n this.events.emit(\"allTabsInactive\", {}, {}, { skipGlobal: true });\n return;\n }\n\n if (tabId === this.tabId) {\n this.events.emit(\"currentTabActivated\", {}, {}, { skipGlobal: true });\n return;\n }\n\n this.events.emit(\"currentTabInactivated\", {}, {}, { skipGlobal: true });\n });\n }\n\n private listenActiveTourTabChange() {\n this.tourState.onTabChange((tabId: string) => {\n if (tabId !== this.tabId) {\n this.events.emit(\"otherTabTookoverTheTour\", {}, {}, { skipGlobal: true });\n }\n });\n }\n\n private listenTabsChange() {\n this.tabState.onTabsChange((tabs: string[]) => {\n this.events.emit(\"tabsChanged\", { tabs }, {}, { skipGlobal: true });\n });\n }\n\n private handleTabClose() {\n this.tabState.clearTab(this.tabId);\n }\n\n private handleTabVisibilityChange() {\n const isTabOnBackground = getWindow().document.visibilityState === \"hidden\";\n if (isTabOnBackground) {\n this.tabState.clearActiveTab();\n return;\n }\n\n this.tabState.setActiveTab(this.tabId);\n }\n}\n","import { TourLifecycleManager } from \"@/lib/tour/tourLifecycleManager\";\nimport { omit, sortBy } from \"lodash-es\";\nimport { autorun, makeAutoObservable, reaction, runInAction, toJS } from \"mobx\";\nimport * as models from \"@common/models\";\nimport { replaceAll, toTitleCase } from \"@/lib/utils\";\nimport { reloadWindow } from \"@/lib/window\";\nimport { PyneClient } from \"@/PyneClient\";\nimport { globalEventBus } from \"@/lib/events/eventBus\";\nimport { DebuggerStateStorage } from \"@/lib/tour/persistent-storage/debuggerState\";\nimport { PyneSettings } from \"@common/schemas\";\nimport { FlowKey } from \"@/lib/tour/tourPlayback/flow\";\nimport { GuideRegistry } from \"./GuideRegistry\";\nimport { GuideTargetingEvaluator } from \"./GuideTargetingEvaluator\";\nimport { UserStateStorage } from \"@/lib/tour/persistent-storage/userState\";\n\nexport interface DebuggerManagerParams {\n tourLifecycleManager: TourLifecycleManager;\n pyneClient: PyneClient;\n storage: DebuggerStateStorage;\n userStateStorage: UserStateStorage;\n pyneSettings: PyneSettings;\n guideRegistry: GuideRegistry;\n guideTargetingEvaluator: GuideTargetingEvaluator;\n}\n\nexport type AdvancedDetailsTab = \"guide\" | \"targeting\" | \"step\" | \"state\";\n\nexport class DebuggerManager {\n isMinimized = true;\n isTourDetailsOpenedFromGuideList = false;\n isGuideListModalVisible = false;\n isTourDetailsModalVisible = false;\n isAdvancedDetailsEnabled = false;\n isUserDataModalVisible = false;\n isReportBugModalVisible = false;\n isStateDataModalVisible = false;\n tourDetailsModalWidth = 280;\n advancedDetailsTab: AdvancedDetailsTab = \"targeting\";\n selectedFlowKey: FlowKey | null = null;\n tourLifecycleManager: TourLifecycleManager;\n guideRegistry: GuideRegistry;\n guideTargetingEvaluator: GuideTargetingEvaluator;\n pyneClient: PyneClient;\n storage: DebuggerStateStorage;\n userStateStorage: UserStateStorage;\n pyneSettings: PyneSettings;\n selectedGuideId?: string;\n selectedStepId?: string;\n isSubmitBugLoading = false;\n isSubmitBugSuccess = false;\n isSubmitBugFailed = false;\n isDevModeEnabled = false;\n\n bugReportId?: string;\n\n constructor({\n tourLifecycleManager,\n pyneClient,\n storage,\n userStateStorage,\n pyneSettings,\n guideRegistry,\n guideTargetingEvaluator,\n }: DebuggerManagerParams) {\n makeAutoObservable(this);\n this.tourLifecycleManager = tourLifecycleManager;\n this.pyneClient = pyneClient;\n this.storage = storage;\n this.pyneSettings = pyneSettings;\n this.guideRegistry = guideRegistry;\n this.userStateStorage = userStateStorage;\n\n const {\n isMinimized,\n isAdvancedDetailsEnabled,\n isGuideListModalVisible,\n isReportBugModalVisible,\n isTourDetailsModalVisible,\n isTourDetailsOpenedFromGuideList,\n isUserDataModalVisible,\n isStateDataModalVisible,\n isDevModeEnabled,\n selectedGuideId,\n selectedStepId,\n advancedDetailsTab,\n } = this.storage.get();\n\n this.isMinimized = isMinimized;\n this.isAdvancedDetailsEnabled = isAdvancedDetailsEnabled;\n this.isGuideListModalVisible = isGuideListModalVisible;\n this.isReportBugModalVisible = isReportBugModalVisible;\n this.isTourDetailsModalVisible = isTourDetailsModalVisible;\n this.isTourDetailsOpenedFromGuideList = isTourDetailsOpenedFromGuideList;\n this.isUserDataModalVisible = isUserDataModalVisible;\n this.isStateDataModalVisible = isStateDataModalVisible;\n this.selectedGuideId = selectedGuideId;\n this.selectedStepId = selectedStepId;\n this.advancedDetailsTab = advancedDetailsTab as AdvancedDetailsTab;\n this.isDevModeEnabled = isDevModeEnabled;\n this.guideTargetingEvaluator = guideTargetingEvaluator;\n\n reaction(\n () => this.tourLifecycleManager.currentTour,\n (currentTour) => {\n if (currentTour) {\n this.followRunningStep();\n this.setAdvancedDetailsTab(\"step\");\n } else {\n this.setAdvancedDetailsTab(\"targeting\");\n this.stopFollowActiveStep();\n this.setSelectedFlowKey(null);\n this.selectedStepId = undefined;\n }\n }\n );\n\n reaction(\n () => this.tourPlaybackManager?.currentFlowKey,\n (flowKey) => {\n this.setSelectedFlowKey(flowKey ?? null);\n }\n );\n\n autorun(() => {\n this.storage.set({\n isMinimized: this.isMinimized,\n isAdvancedDetailsEnabled: this.isAdvancedDetailsEnabled,\n isTourDetailsOpenedFromGuideList: this.isTourDetailsOpenedFromGuideList,\n isGuideListModalVisible: this.isGuideListModalVisible,\n isTourDetailsModalVisible: this.isTourDetailsModalVisible,\n isUserDataModalVisible: this.isUserDataModalVisible,\n isReportBugModalVisible: this.isReportBugModalVisible,\n isStateDataModalVisible: this.isStateDataModalVisible,\n selectedGuideId: this.selectedGuideId,\n selectedStepId: this.selectedStepId,\n advancedDetailsTab: this.advancedDetailsTab,\n isDevModeEnabled: this.isDevModeEnabled,\n });\n });\n\n globalEventBus.use(\"*\", (context) => {\n return {\n ...context,\n pageContext: {\n page: {\n path: location.pathname,\n search: location.search,\n title: document.title,\n url: location.href,\n },\n userAgentData: (navigator as any).userAgentData,\n userAgent: navigator.userAgent,\n locale: navigator.language,\n },\n };\n });\n }\n\n minimize() {\n this.isMinimized = true;\n }\n\n expand() {\n this.isMinimized = false;\n }\n\n openGuideList() {\n this.closeUserDataModal();\n this.closeTourDetails();\n this.isGuideListModalVisible = true;\n }\n\n closeGuideList() {\n this.isGuideListModalVisible = false;\n }\n\n closeTourDetails() {\n this.isTourDetailsModalVisible = false;\n this.isTourDetailsOpenedFromGuideList = false;\n this.selectedGuideId = undefined;\n }\n\n onGuideListButtonClicked() {\n if (this.isGuideListModalVisible) {\n this.closeGuideList();\n return;\n }\n\n this.closeAllModals();\n this.isGuideListModalVisible = true;\n }\n\n onTourDetailsButtonClicked() {\n if (this.isTourDetailsModalVisible) {\n this.closeTourDetails();\n return;\n }\n\n this.closeAllModals();\n this.isTourDetailsModalVisible = true;\n this.selectedGuideId = this.runningGuide?.id;\n }\n\n openTourDetails() {\n this.closeGuideList();\n this.closeUserDataModal();\n this.isTourDetailsModalVisible = true;\n }\n\n toggleReportBugModal() {\n if (this.isReportBugModalVisible) {\n this.closeReportBugModal();\n return;\n }\n\n this.closeAllModals();\n this.isReportBugModalVisible = true;\n }\n\n closeReportBugModal() {\n this.isReportBugModalVisible = false;\n }\n\n closeAllModals() {\n this.closeUserDataModal();\n this.closeGuideList();\n this.closeTourDetails();\n this.closeReportBugModal();\n this.closeStateDataModal();\n }\n\n closeUserDataModal() {\n this.isUserDataModalVisible = false;\n }\n\n toggleUserDataModal() {\n if (this.isUserDataModalVisible) {\n this.closeUserDataModal();\n return;\n }\n\n this.closeAllModals();\n this.isUserDataModalVisible = true;\n }\n\n toggleStateDataModal() {\n if (this.isStateDataModalVisible) {\n this.closeStateDataModal();\n return;\n }\n\n this.closeAllModals();\n this.isStateDataModalVisible = true;\n }\n\n closeStateDataModal() {\n this.isStateDataModalVisible = false;\n }\n\n selectGuide(guideId: string) {\n this.selectedGuideId = guideId;\n this.advancedDetailsTab = \"guide\";\n this.isTourDetailsOpenedFromGuideList = true;\n this.closeGuideList();\n this.openTourDetails();\n }\n\n setAdvancedDetailsEnabled(isEnabled: boolean) {\n this.isAdvancedDetailsEnabled = isEnabled;\n }\n\n setAdvancedDetailsTab(tab: AdvancedDetailsTab) {\n this.advancedDetailsTab = tab;\n }\n\n setTourDetailsModalWidth(width: number) {\n this.tourDetailsModalWidth = width;\n }\n\n clearState() {\n this.tourLifecycleManager.clearState();\n reloadWindow();\n }\n\n get isTourActive() {\n return !!this.tourPlaybackManager;\n }\n\n get selectedGuide() {\n if (!this.selectedGuideId) return null;\n return this.guideRegistry.findById(this.selectedGuideId);\n }\n\n get currentGuideTargetingDetails() {\n if (!this.currentGuide) return null;\n return this.getGuideEvaluationResult(this.currentGuide.id) ?? null;\n }\n\n get currentTourPlayback() {\n return this.selectedGuide?.tour_playback ?? this.tourPlaybackManager?.tourPlayback;\n }\n\n get runningFlow() {\n return this.tourPlaybackManager?.currentFlow ?? null;\n }\n\n get currentFlow() {\n if (this.selectedFlowKey) {\n return this.tourPlaybackManager?.flows[this.selectedFlowKey] ?? null;\n }\n\n return this.runningFlow;\n }\n\n get runningFlowKey() {\n return this.tourPlaybackManager?.currentFlow?.key ?? null;\n }\n\n get selectedFlowState() {\n if (!this.selectedFlowKey) return null;\n return this.getFlowState(this.selectedFlowKey);\n }\n\n getFlowState(flowKey: FlowKey) {\n if (!this.tourPlaybackManager) return null;\n\n const isFallbackFlowStateRequested = flowKey !== \"tour\";\n if (isFallbackFlowStateRequested) {\n return this.tourPlaybackManager.flowState;\n }\n\n const isRunningFallbackFlow = this.runningFlowKey !== \"tour\";\n if (isRunningFallbackFlow) {\n const flowStateStack = this.tourPlaybackManager.flowStateStack;\n return flowStateStack[flowStateStack.length - 1];\n }\n\n return this.tourPlaybackManager.flowState;\n }\n\n get isTourDetailsModalBackButtonVisible() {\n return this.isTourDetailsOpenedFromGuideList;\n }\n\n get currentGuideFormattedTargetingResult() {\n const status = this.currentGuideTargetingDetails?.details.message as string;\n return !!status && status !== \"\" ? toTitleCase(replaceAll(status, \"_\", \" \")) : \"Unknown\";\n }\n\n // Represents the guide that is currently showed in tour details modal\n get currentGuide() {\n return this.selectedGuide ? new models.Guide(this.selectedGuide) : this.tourLifecycleManager.currentGuide;\n }\n\n get tourPlaybackManager() {\n return this.tourLifecycleManager.currentTour;\n }\n\n get runningGuide() {\n return this.tourLifecycleManager.currentGuide;\n }\n\n get currentStep() {\n return this.selectedStep ?? this.runningStep;\n }\n\n get runningStep() {\n return this.tourPlaybackManager?.currentStep;\n }\n\n get runningSection() {\n return this.tourPlaybackManager?.currentSection;\n }\n\n get currentSection() {\n const isSelectedStepDifferentFromRunningStep =\n this.selectedStepId && this.runningStep && this.selectedStepId !== this.runningStep.id;\n if (isSelectedStepDifferentFromRunningStep) {\n return this.currentFlow?.sections.find((s) => s.steps.find((step) => step.id === this.selectedStepId)) ?? null;\n }\n return this.runningSection ?? null;\n }\n\n get activeFlowKey() {\n return this.tourPlaybackManager?.currentFlow?.key ?? null;\n }\n\n isGuideRunning(guideId: string) {\n if (!this.tourLifecycleManager.currentGuide) return false;\n return this.tourLifecycleManager.currentGuide.id === guideId;\n }\n\n get isCurrentGuideRunning() {\n if (!this.currentGuide || !this.runningGuide) return false;\n\n return this.isGuideRunning(this.currentGuide.id);\n }\n\n setSelectedFlowKey(flowKey: FlowKey | null) {\n this.selectedFlowKey = flowKey;\n }\n\n get selectedStep() {\n if (!this.selectedStepId) return null;\n\n const stepInGuide = this.findStepInCurrentGuide(this.selectedStepId);\n if (stepInGuide) return new models.Step(stepInGuide);\n\n const isCurrentGuideActive = this.currentGuide && this.isGuideRunning(this.currentGuide.id);\n if (isCurrentGuideActive) {\n const stepInFlow = this.findStepInRunningFlow(this.selectedStepId);\n if (stepInFlow) return new models.Step(stepInFlow);\n }\n\n return null;\n }\n\n get isRunningFlowExists() {\n return !!this.runningFlow;\n }\n\n get isRunningTourFlow() {\n return !!this.runningFlow?.key && this.runningFlow.key === \"tour\";\n }\n\n findStepInCurrentGuide(stepId: string) {\n return this.currentGuide?.tour_playback?.sections.flatMap((s) => s.steps).find((s) => s.id === stepId);\n }\n\n findStepInRunningFlow(stepId: string) {\n return this.runningFlow?.sections.flatMap((s) => s.steps).find((s) => s.id === stepId);\n }\n\n isStepOnTrack(stepId: string) {\n if (!this.tourPlaybackManager) return true;\n return this.tourPlaybackManager.tourTrackManager.isOnTrack(stepId);\n }\n\n get currentStepOnTrackResult() {\n if (!this.currentStep) return undefined;\n return this.tourPlaybackManager?.tourTrackManager.getResult(this.currentStep.id);\n }\n\n get currentStepDetailedOnTrackResult() {\n if (!this.currentStep) return undefined;\n return this.tourPlaybackManager?.tourTrackManager.getDetailedResult(this.currentStep.id);\n }\n\n selectStep(stepId: string) {\n this.selectedStepId = stepId;\n if (stepId === this.runningStep?.id) {\n this.followRunningStep();\n } else {\n this.stopFollowActiveStep();\n }\n\n if (!this.isAdvancedDetailsEnabled) {\n this.isAdvancedDetailsEnabled = true;\n }\n\n this.setAdvancedDetailsTab(\"step\");\n }\n\n clearSelectedStep() {\n this.selectedStepId = undefined;\n }\n\n stopFollowRunningStepFn?: () => void;\n\n followRunningStep() {\n this.stopFollowRunningStepFn = autorun(() => {\n this.selectedStepId = this.runningStep?.id;\n });\n }\n\n stopFollowActiveStep() {\n this.stopFollowRunningStepFn?.();\n this.stopFollowRunningStepFn = undefined;\n }\n\n get guides() {\n return sortBy(this.guideRegistry.guides, (guide) => new Date(guide.created_at).toISOString()).reverse();\n }\n\n getGuideEvaluationResult(guideId: string) {\n return this.guideTargetingEvaluator.findResultById(guideId);\n }\n\n getGuideEvaluationStatus(guideId: string) {\n const result = this.getGuideEvaluationResult(guideId);\n if (!result) return \"Unknown\";\n\n return (result.details.message as string) ?? \"Unknown\";\n }\n\n startTour() {\n if (!this.selectedGuide) return;\n this.tourLifecycleManager.terminateCurrentTourAndStartNewTour(\n new models.Guide(this.selectedGuide),\n \"trigger_from_debugger\",\n \"trigger_from_debugger\"\n );\n }\n\n startTourFromStep(stepId: string) {\n if (!this.selectedGuide) return;\n this.tourLifecycleManager.terminateCurrentTourAndStartNewTour(\n new models.Guide(this.selectedGuide),\n \"trigger_from_debugger\",\n \"trigger_from_debugger\",\n {\n tourStartStrategy: { type: \"resume\", stepId },\n }\n );\n }\n\n terminateCurrentTour() {\n this.tourLifecycleManager.terminateCurrentTour(\"trigger_from_debugger\");\n }\n\n get currentUser() {\n return this.pyneClient.currentUser;\n }\n\n get isEnabled() {\n return this.storage.isEnabled;\n }\n\n enableDevMode() {\n this.isDevModeEnabled = true;\n }\n\n get tourStartParams() {\n const initialTourStateSnapshot = this.initialTourStateSnapshot;\n const lastCheckpoint = initialTourStateSnapshot?.checkpoints?.[initialTourStateSnapshot?.checkpoints.length - 1];\n return {\n activeStepId: initialTourStateSnapshot?.activeStepId ?? \"-\",\n lastCompletedStepId: initialTourStateSnapshot?.lastCompletedStepId ?? \"-\",\n lastCheckpoitStepId: lastCheckpoint?.stepId ?? \"-\",\n lastCheckpointUrl: lastCheckpoint?.url ?? \"-\",\n lastPageUrl: initialTourStateSnapshot?.lastPageUrl ?? \"-\",\n isSuspended: initialTourStateSnapshot?.isSuspended ?? \"-\",\n tabId: initialTourStateSnapshot?.tabId ?? \"-\",\n };\n }\n\n get initialTourStateSnapshot() {\n return this.tourLifecycleManager.tourStartManager.initialTourStateSnapshot;\n }\n\n get tourPlaybackFlowContext() {\n const flowState = this.tourPlaybackManager?.flowState;\n return {\n currentTime: flowState?.currentTime,\n currentSectionIndex: flowState?.currentSectionIndex,\n currentStepIndex: flowState?.currentStepIndex,\n };\n }\n\n get tourPlaybackFlowStatus() {\n return this.tourPlaybackManager?.flowStatus;\n }\n\n get avatarState() {\n return this.tourPlaybackManager?.avatarManager.state?.value;\n }\n\n get avatarManager() {\n return this.tourPlaybackManager?.avatarManager;\n }\n\n get tourStartStrategy() {\n return this.tourLifecycleManager.lastTourStartStrategy;\n }\n\n get userState() {\n return {\n finishedTourGuideIds: this.userStateStorage.finishedTourGuideIds,\n dismissedTourGuideIds: this.userStateStorage.dismissedTourGuideIds,\n };\n }\n\n isCheckpointCaptured(stepId: string) {\n return !!this.tourPlaybackManager?.checkpoints.find((checkpoint) => checkpoint.stepId === stepId);\n }\n}\n","import { makeAutoObservable, runInAction } from \"mobx\";\nimport { store, type RootStore } from \"@/store\";\n\nexport class WidgetPositioner {\n constructor(public rootStore: RootStore) {\n makeAutoObservable(this);\n }\n\n get subtitlesBottomOffset() {\n if (store.pyneSettings.debug) {\n return 28;\n }\n\n return 16;\n }\n\n get promptBottomOffset() {\n if (store.pyneSettings.debug) {\n return 96;\n }\n\n return 84;\n }\n\n get additionalContentBottomOffset() {\n if (store.pyneSettings.debug) {\n return 206;\n }\n\n return 194;\n }\n\n get stylesheetContent() {\n const content = `\n #pyne-subtitles {\n bottom: ${this.subtitlesBottomOffset}px;\n }\n\n #pyne-prompt {\n bottom: ${this.promptBottomOffset}px;\n }\n\n #pyne-additional-content{\n bottom: ${this.additionalContentBottomOffset}px;\n }\n `;\n return content;\n }\n}\n","import { RawGuide } from \"@common/api/ping\";\nimport { makeObservable, observable } from \"mobx\";\n\nexport class GuideRegistry {\n _guides: RawGuide[] = [];\n\n constructor() {\n makeObservable(this, {\n _guides: observable.ref,\n });\n }\n\n setGuides(guides: RawGuide[]) {\n this._guides = guides;\n }\n\n findById(id: string) {\n return this._guides.find((guide) => guide.id === id);\n }\n\n get guides() {\n return this._guides;\n }\n}\n","import { makeAutoObservable } from \"mobx\";\nimport { log } from \"./lib/log\";\nimport { RootStore } from \"./store\";\n\n/**\n * This store is responsible for preloading additional content assets for the tour.\n */\nexport class AssetManager {\n cache = new Map();\n queue: string[] = [];\n isLoading = false;\n\n constructor(public rootStore: RootStore) {\n makeAutoObservable(this);\n }\n\n init() {\n this.rootStore.tourLifecycleManager.events.on(\"tourStarted\", () => {\n this.clearCache();\n this.preloadTourStepAssets();\n });\n this.rootStore.tourLifecycleManager.events.on(\"tourFinished\", () => this.clearCache());\n this.rootStore.tourLifecycleManager.events.on(\"tourTerminated\", () => this.clearCache());\n }\n\n getAsset(url: string) {\n if (this.rootStore.pyneSettings.skipBlobMediaPreload) {\n return { url, cached: false };\n }\n\n let objectUrl: string | undefined = undefined;\n if (this.cache.has(url)) {\n objectUrl = this.cache.get(url)!;\n }\n return objectUrl ? { url: objectUrl, cached: true } : { url, cached: false };\n }\n\n private preloadTourStepAssets() {\n log(\"AssetManager:\", \"preloading tour step assets\");\n\n if (!this.rootStore.currentTour) return;\n const tour = this.rootStore.currentTour;\n\n const urls = [];\n for (const step of tour.nextSteps) {\n for (const asset of step.assetUrls) {\n urls.push(asset.src);\n }\n }\n\n this.queue.push(...urls);\n this.loadAssets();\n }\n\n clearCache() {\n Object.values(this.cache).forEach((url) => URL.revokeObjectURL(url));\n this.cache.clear();\n }\n\n private async loadAssets() {\n if (this.isLoading) return;\n this.isLoading = true;\n while (this.queue.length) {\n const url = this.queue.shift()!;\n try {\n await this.fetch(url);\n } catch (e) {\n console.error(e);\n }\n }\n this.isLoading = true;\n }\n\n private async fetch(url: string) {\n if (this.cache.has(url)) return;\n const response = await fetch(url);\n const blob = await response.blob();\n const objectUrl = URL.createObjectURL(blob);\n this.cache.set(url, objectUrl);\n log(\"AssetManager:\", \"prefetched\", url);\n }\n}\n","import { GuideScheduleReason } from \"./guideScheduler\";\nimport { TourTerminateReason } from \"./tourLifecycleManager\";\n\nexport type TourSessionManagerEvents = {\n tourSessionExpired: { sessionId: string };\n tourSessionStarted: { sessionId: string; startedAt: number; reason: GuideScheduleReason };\n tourSessionResumed: { sessionId: string };\n tourSessionTerminated: { sessionId: string; reason: TourTerminateReason };\n};\n\nexport const TourSessionManagerNamespace = \"tourSessionManager\" as const;\n","import { EventEmitter } from \"../events/eventEmitter\";\nimport { log } from \"../log\";\nimport { GuideScheduleReason } from \"./guideScheduler\";\nimport { SessionStateStorage } from \"./persistent-storage/sessionState\";\nimport { TourState, TourStateStorage } from \"./persistent-storage/tourState\";\nimport { TourTerminateReason } from \"./tourLifecycleManager\";\nimport { TourSessionManagerEvents, TourSessionManagerNamespace } from \"./tourSessionManager.events\";\n\nexport interface TourSessionManagerParams {\n tourStateStorage: TourStateStorage;\n sessionStateStorage: SessionStateStorage;\n}\n\nexport type TourSession = {\n sessionId: string;\n startedAt: number;\n};\n\nexport class TourSessionManager {\n private tourStateStorage: TourStateStorage;\n private sessionStateStorage: SessionStateStorage;\n static readonly defaultTourExpirationDuration = 10000;\n private expirationCheckTimer: NodeJS.Timeout | undefined;\n events = new EventEmitter(TourSessionManagerNamespace);\n activeSessionId?: string;\n\n constructor({ tourStateStorage, sessionStateStorage }: TourSessionManagerParams) {\n this.tourStateStorage = tourStateStorage;\n this.sessionStateStorage = sessionStateStorage;\n this.activeSessionId = this.tourStateStorage.get().sessionId;\n this.clearTourSessionIfExpired();\n }\n\n initializeTourSession(reason: GuideScheduleReason): TourSession {\n const startedAt = this.tourStateStorage.initStartedAt();\n const sessionId = this.tourStateStorage.initSessionId();\n this.activeSessionId = sessionId;\n if (reason === \"tour_session_recovered\") {\n this.events.emit(\"tourSessionResumed\", { sessionId });\n } else {\n this.events.emit(\"tourSessionStarted\", { sessionId, startedAt, reason });\n }\n\n this.startExpirationTimer();\n\n return {\n startedAt,\n sessionId,\n };\n }\n\n terminateTourSession(reason: TourTerminateReason) {\n if (!this.activeSessionId) {\n return;\n }\n\n this.events.emit(\"tourSessionTerminated\", { reason, sessionId: this.activeSessionId });\n this.stopExpirationTimer();\n this.activeSessionId = undefined;\n this.tourStateStorage.clear();\n }\n\n getRecoverableTourSession(): TourState | undefined {\n const tourState = this.tourStateStorage.get();\n if (!tourState.activeTourGuideId) {\n return undefined;\n }\n\n if (this.isTourSessionExpired(tourState)) {\n return undefined;\n }\n\n return tourState;\n }\n\n isTourSessionExpired(tourState: TourState): boolean {\n const lastStepTransitionTimestamp = tourState.lastStepTransitionTimestamp;\n const sessionStartedAt = tourState.startedAt;\n\n let tZero: number | undefined;\n\n if (lastStepTransitionTimestamp) {\n tZero = lastStepTransitionTimestamp;\n }\n\n if (!tZero && sessionStartedAt) {\n tZero = sessionStartedAt;\n }\n\n if (!tZero) {\n return true;\n }\n\n const expirationTimeoutDuration = tourState.expirationTimeoutMinutes\n ? tourState.expirationTimeoutMinutes * 60 * 1000\n : TourSessionManager.defaultTourExpirationDuration;\n\n const timePassed = Date.now() - tZero;\n return timePassed > expirationTimeoutDuration;\n }\n\n private clearTourSessionIfExpired(): boolean {\n const tourState = this.tourStateStorage.get();\n if (!tourState.activeTourGuideId) {\n return false;\n }\n\n if (this.isTourSessionExpired(tourState)) {\n this.terminateTourSession(\"session_expired\");\n this.sessionStateStorage.addExpiredGuide(tourState.activeTourGuideId);\n this.events.emit(\"tourSessionExpired\", { sessionId: tourState.sessionId! });\n return true;\n }\n\n return false;\n }\n\n private startExpirationTimer() {\n if (this.expirationCheckTimer) {\n clearInterval(this.expirationCheckTimer);\n }\n\n // Check every 10 seconds\n this.expirationCheckTimer = setInterval(() => {\n const tourState = this.tourStateStorage.get();\n if (this.isTourSessionExpired(tourState)) {\n log(\"Tour session has expired\");\n\n this.sessionStateStorage.addExpiredGuide(tourState.activeTourGuideId!);\n this.events.emit(\"tourSessionExpired\", { sessionId: tourState.sessionId! });\n this.stopExpirationTimer();\n }\n }, 10000);\n }\n\n private stopExpirationTimer() {\n if (this.expirationCheckTimer) {\n window.clearInterval(this.expirationCheckTimer);\n this.expirationCheckTimer = undefined;\n }\n }\n}\n","import { PersistentStorage } from \"@/lib/tour/persistent-storage/storage\";\nimport { TourLifecycleManager, TourTerminateReason } from \"@/lib/tour/tourLifecycleManager\";\nimport { TourPlaybackManager } from \"@/lib/tour/tourPlayback/tourPlaybackManager\";\nimport { getWindow, navigateTo } from \"@/lib/window\";\nimport { store } from \"@/store\";\nimport { makeAutoObservable } from \"mobx\";\n\nexport class PreviewManager {\n storage: PersistentStorage;\n tourLifecycleManager!: TourLifecycleManager;\n\n constructor({\n storage,\n tourLifecycleManager,\n }: {\n storage: PersistentStorage;\n tourLifecycleManager: TourLifecycleManager;\n }) {\n makeAutoObservable(this);\n this.storage = storage;\n this.tourLifecycleManager = tourLifecycleManager;\n }\n\n terminateCurrentTour(reason: TourTerminateReason) {\n this.tourLifecycleManager.terminateCurrentTour(reason);\n }\n\n restartPreview() {\n const previewGuideId = this.storage.previewState.getGuideId();\n const initialUrl = this.storage.previewState.get().initialUrl;\n if (previewGuideId) {\n if (this.tourLifecycleManager.currentTour) {\n this.terminateCurrentTour(\"restart_preview\");\n this.storage.previewState.clear();\n }\n if (initialUrl) {\n navigateTo(initialUrl);\n return true;\n }\n }\n return false;\n }\n\n closePreview() {\n store.disableDebug();\n this.storage.previewState.clear();\n const url = new URL(window.location.href);\n url.searchParams.delete(\"pyne-guide-id\");\n window.history.replaceState({}, \"\", url);\n\n if (this.tourLifecycleManager.currentTour) {\n this.terminateCurrentTour(\"close_preview\");\n }\n store.disablePreview();\n }\n}\n","import { makeAutoObservable, runInAction } from \"mobx\";\nimport { Guide } from \"@common/models\";\nimport type { PyneSettings } from \"./global\";\nimport { log } from \"./lib/log\";\nimport { SyncManager } from \"./lib/SyncManager\";\nimport { TourAnalyticsCollector } from \"./lib/tour/tourAnalyticsCollector\";\nimport { TourLifecycleManager } from \"./lib/tour/tourLifecycleManager\";\nimport { TourPlaybackManager } from \"./lib/tour/tourPlayback\";\nimport { PyneClient } from \"./PyneClient\";\nimport { GuideTargetingEvaluator } from \"./stores/GuideTargetingEvaluator\";\nimport { GuideScheduler } from \"./lib/tour/guideScheduler\";\nimport { createLocalStorageHandler, createSessionStorageHandler } from \"./lib/storage\";\nimport { PersistentStorage } from \"./lib/tour/persistent-storage/storage\";\nimport { AvatarPositioner } from \"./stores/AvatarPositioner\";\nimport { TourStartManager } from \"./lib/tour/tourStartManager\";\nimport { TabManager } from \"./lib/tour/tabManager\";\nimport { DebuggerManager } from \"./stores/DebuggerManager\";\nimport { WidgetPositioner } from \"./stores/PromptPositioner\";\nimport { GuideRegistry } from \"./stores/GuideRegistry\";\nimport { AssetManager } from \"./AssetManager\";\nimport invariant from \"ts-invariant\";\nimport { TourSessionManager } from \"./lib/tour/tourSessionManager\";\nimport { PreviewManager } from \"./stores/PreviewManager\";\n\nconst defaultPyneSettings: Partial = {\n pointerType: \"dot\",\n api_base: \"https://dashboard.pyne.ai/api\",\n};\n\nexport class RootStore {\n pyneClient: PyneClient;\n currentGuide?: Guide;\n currentTour?: TourPlaybackManager;\n pyneSettings: PyneSettings;\n urlPreviewGuideId?: string;\n sharedGuideId?: string;\n isMuted = false;\n showCaptions = true;\n syncManager: SyncManager;\n tourLifecycleManager!: TourLifecycleManager;\n guideTargetingEvaluator!: GuideTargetingEvaluator;\n guideScheduler!: GuideScheduler;\n tourStartManager!: TourStartManager;\n tabManager!: TabManager;\n tourSessionManager!: TourSessionManager;\n avatarPosition = new AvatarPositioner(this);\n widgetPosition = new WidgetPositioner(this);\n debuggerManager!: DebuggerManager;\n guideRegistry: GuideRegistry;\n private storage: PersistentStorage;\n public isPreview = false;\n assetManager = new AssetManager(this);\n previewManager!: PreviewManager;\n constructor() {\n makeAutoObservable(this);\n\n this.pyneClient = new PyneClient(this);\n\n this.pyneSettings = { ...defaultPyneSettings };\n this.guideRegistry = new GuideRegistry();\n this.syncManager = new SyncManager({\n rootStore: this,\n pyneClient: this.pyneClient,\n guideRegistry: this.guideRegistry,\n });\n this.storage = new PersistentStorage({\n localStorageHandler: createLocalStorageHandler(),\n sessionStorageHandler: createSessionStorageHandler(),\n });\n\n const previewGuideId = new URLSearchParams(location.search).get(\"pyne-guide-id\") ?? undefined;\n const existingPreviewGuideId = this.storage.previewState.getGuideId();\n const previewGuideIdToBeStarted = previewGuideId ?? existingPreviewGuideId;\n this.urlPreviewGuideId = previewGuideIdToBeStarted;\n if (previewGuideIdToBeStarted) {\n this.isPreview = true;\n this.storage.enablePreviewMode();\n this.storage.previewState.enable(previewGuideIdToBeStarted);\n this.storage.debuggerState.enable();\n }\n\n const sharedGuideId = new URLSearchParams(location.search).get(\"pyne-shared-guide-id\") ?? undefined;\n this.sharedGuideId = sharedGuideId;\n }\n\n setPyneSettings(pyneSettings: PyneSettings) {\n this.pyneSettings = { ...defaultPyneSettings, ...pyneSettings };\n validateApiUrl(this.pyneSettings.api_base);\n }\n\n init() {\n if (!this.pyneSettings.api_base || !this.pyneSettings.app_id) {\n log(\"Pyne settings not found\");\n return;\n }\n\n this.tourStartManager = new TourStartManager();\n this.guideTargetingEvaluator = new GuideTargetingEvaluator({\n syncManager: this.syncManager,\n storage: this.storage,\n guideRegistry: this.guideRegistry,\n });\n this.tourSessionManager = new TourSessionManager({\n tourStateStorage: this.storage.tourState,\n sessionStateStorage: this.storage.sessionState,\n });\n this.guideScheduler = new GuideScheduler({\n guideTargetingEvaluator: this.guideTargetingEvaluator,\n pyneClient: this.pyneClient,\n syncManager: this.syncManager,\n guideRegistry: this.guideRegistry,\n storage: this.storage,\n tourSessionManager: this.tourSessionManager,\n options: {\n previewGuideId: this.urlPreviewGuideId,\n sharedGuideId: this.sharedGuideId,\n },\n });\n this.tabManager = new TabManager({\n tabState: this.storage.tabState,\n tourState: this.storage.tourState,\n });\n this.tourLifecycleManager = new TourLifecycleManager({\n tabManager: this.tabManager,\n tourStartManager: this.tourStartManager,\n guideScheduler: this.guideScheduler,\n storage: this.storage,\n tourSessionManager: this.tourSessionManager,\n skipBlobMediaPreload: this.pyneSettings.skipBlobMediaPreload,\n mediaPlaybackRate: this.pyneSettings.mediaPlaybackRate,\n pyneSettings: this.pyneSettings,\n });\n\n if (this.isPreview && this.urlPreviewGuideId) {\n this.previewManager = new PreviewManager({\n storage: this.storage,\n tourLifecycleManager: this.tourLifecycleManager,\n });\n }\n\n if (!this.isPreview) {\n TourAnalyticsCollector.init({\n appId: this.pyneSettings.app_id,\n apiBaseUrl: this.pyneSettings.api_base,\n getUser: () => {\n return {\n user_id: this.pyneClient.currentUser?.id,\n user_traits: this.pyneClient.currentUser?.traits,\n anonymous_id: this.pyneClient.anonymousId ?? undefined,\n };\n },\n });\n }\n\n const isDebugOptionNotSpecified = this.pyneSettings.debug === undefined;\n if (isDebugOptionNotSpecified) {\n this.pyneSettings.debug = this.storage.debuggerState.isEnabled;\n } else if (this.pyneSettings.debug) {\n this.storage.debuggerState.enable();\n }\n\n this.debuggerManager = new DebuggerManager({\n tourLifecycleManager: this.tourLifecycleManager,\n pyneClient: this.pyneClient,\n storage: this.storage.debuggerState,\n pyneSettings: this.pyneSettings,\n guideRegistry: this.guideRegistry,\n guideTargetingEvaluator: this.guideTargetingEvaluator,\n userStateStorage: this.storage.userState,\n });\n\n this.tourLifecycleManager.events.on(\"tourInitialized\", ({ payload: { guide, tour } }) => {\n runInAction(() => {\n log(\"Tour initialized\", tour);\n this.currentGuide = guide;\n this.currentTour = tour;\n });\n });\n\n this.tourLifecycleManager.events.on(\"tourDismissed\", () => {\n runInAction(() => {\n this.currentGuide = undefined;\n this.currentTour = undefined;\n });\n });\n\n this.tourLifecycleManager.events.on(\"tourFinished\", () => {\n runInAction(() => {\n this.currentGuide = undefined;\n this.currentTour = undefined;\n });\n });\n\n this.tourLifecycleManager.events.on(\"tourTerminated\", () => {\n runInAction(() => {\n this.currentGuide = undefined;\n this.currentTour = undefined;\n });\n });\n\n this.tourLifecycleManager.start();\n\n this.assetManager.init();\n }\n\n dismissCurrentTour() {\n this.tourLifecycleManager.dismissCurrentTour();\n }\n\n clearState() {\n this.tourLifecycleManager?.stop();\n this.storage.clearAll();\n }\n\n get isDebugVisible() {\n return this.pyneSettings.debug;\n }\n\n enableDebug() {\n this.pyneSettings.debug = true;\n this.storage.debuggerState.enable();\n }\n\n disableDebug() {\n this.pyneSettings.debug = false;\n this.storage.debuggerState.disable();\n }\n\n disablePreview() {\n this.isPreview = false;\n }\n\n setAvatarInitialPositionRight() {\n this.avatarPosition.isPositionedRight = true;\n }\n}\n\nexport const store = new RootStore();\n\nfunction validateApiUrl(apiBase: string | undefined) {\n invariant(apiBase, \"API base URL is not set\");\n\n const allowedOrigins = [\"https://dashboard.pyne.ai\", \"http://localhost:3000\", \"https://test.pyne.ai\"];\n const origin = new URL(apiBase).origin;\n invariant(allowedOrigins.includes(origin), `API base URL ${apiBase} is not allowed`);\n}\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nvar defaultAttributes = {\n xmlns: \"http://www.w3.org/2000/svg\",\n width: 24,\n height: 24,\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n strokeWidth: 2,\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\"\n};\n\nexport { defaultAttributes as default };\n//# sourceMappingURL=defaultAttributes.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nconst toKebabCase = (string) => string.replace(/([a-z0-9])([A-Z])/g, \"$1-$2\").toLowerCase();\n\nexport { toKebabCase };\n//# sourceMappingURL=utils.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { forwardRef, createElement } from 'react';\nimport defaultAttributes from './defaultAttributes.js';\nimport { toKebabCase } from './shared/src/utils.js';\n\nconst createLucideIcon = (iconName, iconNode) => {\n const Component = forwardRef(\n ({\n color = \"currentColor\",\n size = 24,\n strokeWidth = 2,\n absoluteStrokeWidth,\n className = \"\",\n children,\n ...rest\n }, ref) => {\n return createElement(\n \"svg\",\n {\n ref,\n ...defaultAttributes,\n width: size,\n height: size,\n stroke: color,\n strokeWidth: absoluteStrokeWidth ? Number(strokeWidth) * 24 / Number(size) : strokeWidth,\n className: [\"lucide\", `lucide-${toKebabCase(iconName)}`, className].join(\" \"),\n ...rest\n },\n [\n ...iconNode.map(([tag, attrs]) => createElement(tag, attrs)),\n ...Array.isArray(children) ? children : [children]\n ]\n );\n }\n );\n Component.displayName = `${iconName}`;\n return Component;\n};\n\nexport { createLucideIcon as default };\n//# sourceMappingURL=createLucideIcon.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst Box = createLucideIcon(\"Box\", [\n [\n \"path\",\n {\n d: \"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z\",\n key: \"hh9hay\"\n }\n ],\n [\"path\", { d: \"m3.3 7 8.7 5 8.7-5\", key: \"g66t2b\" }],\n [\"path\", { d: \"M12 22V12\", key: \"d0xqtd\" }]\n]);\n\nexport { Box as default };\n//# sourceMappingURL=box.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst CaptionsOff = createLucideIcon(\"CaptionsOff\", [\n [\"path\", { d: \"M10.5 5H19a2 2 0 0 1 2 2v8.5\", key: \"jqtk4d\" }],\n [\"path\", { d: \"M17 11h-.5\", key: \"1961ue\" }],\n [\"path\", { d: \"M19 19H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2\", key: \"1keqsi\" }],\n [\"path\", { d: \"m2 2 20 20\", key: \"1ooewy\" }],\n [\"path\", { d: \"M7 11h4\", key: \"1o1z6v\" }],\n [\"path\", { d: \"M7 15h2.5\", key: \"1ina1g\" }]\n]);\n\nexport { CaptionsOff as default };\n//# sourceMappingURL=captions-off.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst Captions = createLucideIcon(\"Captions\", [\n [\"rect\", { width: \"18\", height: \"14\", x: \"3\", y: \"5\", rx: \"2\", ry: \"2\", key: \"12ruh7\" }],\n [\"path\", { d: \"M7 15h4M15 15h2M7 11h2M13 11h4\", key: \"1ueiar\" }]\n]);\n\nexport { Captions as default };\n//# sourceMappingURL=captions.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst Check = createLucideIcon(\"Check\", [[\"path\", { d: \"M20 6 9 17l-5-5\", key: \"1gmf2c\" }]]);\n\nexport { Check as default };\n//# sourceMappingURL=check.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst ChevronDown = createLucideIcon(\"ChevronDown\", [\n [\"path\", { d: \"m6 9 6 6 6-6\", key: \"qrunsl\" }]\n]);\n\nexport { ChevronDown as default };\n//# sourceMappingURL=chevron-down.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst ChevronLeft = createLucideIcon(\"ChevronLeft\", [\n [\"path\", { d: \"m15 18-6-6 6-6\", key: \"1wnfg3\" }]\n]);\n\nexport { ChevronLeft as default };\n//# sourceMappingURL=chevron-left.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst ChevronUp = createLucideIcon(\"ChevronUp\", [[\"path\", { d: \"m18 15-6-6-6 6\", key: \"153udz\" }]]);\n\nexport { ChevronUp as default };\n//# sourceMappingURL=chevron-up.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst CircleCheck = createLucideIcon(\"CircleCheck\", [\n [\"circle\", { cx: \"12\", cy: \"12\", r: \"10\", key: \"1mglay\" }],\n [\"path\", { d: \"m9 12 2 2 4-4\", key: \"dzmm74\" }]\n]);\n\nexport { CircleCheck as default };\n//# sourceMappingURL=circle-check.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst CircleHelp = createLucideIcon(\"CircleHelp\", [\n [\"circle\", { cx: \"12\", cy: \"12\", r: \"10\", key: \"1mglay\" }],\n [\"path\", { d: \"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3\", key: \"1u773s\" }],\n [\"path\", { d: \"M12 17h.01\", key: \"p32p05\" }]\n]);\n\nexport { CircleHelp as default };\n//# sourceMappingURL=circle-help.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst Copy = createLucideIcon(\"Copy\", [\n [\"rect\", { width: \"14\", height: \"14\", x: \"8\", y: \"8\", rx: \"2\", ry: \"2\", key: \"17jyea\" }],\n [\"path\", { d: \"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\", key: \"zix9uf\" }]\n]);\n\nexport { Copy as default };\n//# sourceMappingURL=copy.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst Ellipsis = createLucideIcon(\"Ellipsis\", [\n [\"circle\", { cx: \"12\", cy: \"12\", r: \"1\", key: \"41hilf\" }],\n [\"circle\", { cx: \"19\", cy: \"12\", r: \"1\", key: \"1wjl8i\" }],\n [\"circle\", { cx: \"5\", cy: \"12\", r: \"1\", key: \"1pcz8c\" }]\n]);\n\nexport { Ellipsis as default };\n//# sourceMappingURL=ellipsis.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst Expand = createLucideIcon(\"Expand\", [\n [\"path\", { d: \"m21 21-6-6m6 6v-4.8m0 4.8h-4.8\", key: \"1c15vz\" }],\n [\"path\", { d: \"M3 16.2V21m0 0h4.8M3 21l6-6\", key: \"1fsnz2\" }],\n [\"path\", { d: \"M21 7.8V3m0 0h-4.8M21 3l-6 6\", key: \"hawz9i\" }],\n [\"path\", { d: \"M3 7.8V3m0 0h4.8M3 3l6 6\", key: \"u9ee12\" }]\n]);\n\nexport { Expand as default };\n//# sourceMappingURL=expand.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst LandPlot = createLucideIcon(\"LandPlot\", [\n [\"path\", { d: \"m12 8 6-3-6-3v10\", key: \"mvpnpy\" }],\n [\n \"path\",\n {\n d: \"m8 11.99-5.5 3.14a1 1 0 0 0 0 1.74l8.5 4.86a2 2 0 0 0 2 0l8.5-4.86a1 1 0 0 0 0-1.74L16 12\",\n key: \"ek95tt\"\n }\n ],\n [\"path\", { d: \"m6.49 12.85 11.02 6.3\", key: \"1kt42w\" }],\n [\"path\", { d: \"M17.51 12.85 6.5 19.15\", key: \"v55bdg\" }]\n]);\n\nexport { LandPlot as default };\n//# sourceMappingURL=land-plot.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst LoaderCircle = createLucideIcon(\"LoaderCircle\", [\n [\"path\", { d: \"M21 12a9 9 0 1 1-6.219-8.56\", key: \"13zald\" }]\n]);\n\nexport { LoaderCircle as default };\n//# sourceMappingURL=loader-circle.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst Minimize2 = createLucideIcon(\"Minimize2\", [\n [\"polyline\", { points: \"4 14 10 14 10 20\", key: \"11kfnr\" }],\n [\"polyline\", { points: \"20 10 14 10 14 4\", key: \"rlmsce\" }],\n [\"line\", { x1: \"14\", x2: \"21\", y1: \"10\", y2: \"3\", key: \"o5lafz\" }],\n [\"line\", { x1: \"3\", x2: \"10\", y1: \"21\", y2: \"14\", key: \"1atl0r\" }]\n]);\n\nexport { Minimize2 as default };\n//# sourceMappingURL=minimize-2.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst Minimize = createLucideIcon(\"Minimize\", [\n [\"path\", { d: \"M8 3v3a2 2 0 0 1-2 2H3\", key: \"hohbtr\" }],\n [\"path\", { d: \"M21 8h-3a2 2 0 0 1-2-2V3\", key: \"5jw1f3\" }],\n [\"path\", { d: \"M3 16h3a2 2 0 0 1 2 2v3\", key: \"198tvr\" }],\n [\"path\", { d: \"M16 21v-3a2 2 0 0 1 2-2h3\", key: \"ph8mxp\" }]\n]);\n\nexport { Minimize as default };\n//# sourceMappingURL=minimize.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst Pause = createLucideIcon(\"Pause\", [\n [\"rect\", { width: \"4\", height: \"16\", x: \"6\", y: \"4\", key: \"iffhe4\" }],\n [\"rect\", { width: \"4\", height: \"16\", x: \"14\", y: \"4\", key: \"sjin7j\" }]\n]);\n\nexport { Pause as default };\n//# sourceMappingURL=pause.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst Play = createLucideIcon(\"Play\", [\n [\"polygon\", { points: \"6 3 20 12 6 21 6 3\", key: \"1oa8hb\" }]\n]);\n\nexport { Play as default };\n//# sourceMappingURL=play.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst RotateCcw = createLucideIcon(\"RotateCcw\", [\n [\"path\", { d: \"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8\", key: \"1357e3\" }],\n [\"path\", { d: \"M3 3v5h5\", key: \"1xhq8a\" }]\n]);\n\nexport { RotateCcw as default };\n//# sourceMappingURL=rotate-ccw.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst ScrollText = createLucideIcon(\"ScrollText\", [\n [\n \"path\",\n { d: \"M8 21h12a2 2 0 0 0 2-2v-2H10v2a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v3h4\", key: \"13a6an\" }\n ],\n [\"path\", { d: \"M19 17V5a2 2 0 0 0-2-2H4\", key: \"zz82l3\" }],\n [\"path\", { d: \"M15 8h-5\", key: \"1khuty\" }],\n [\"path\", { d: \"M15 12h-5\", key: \"r7krc0\" }]\n]);\n\nexport { ScrollText as default };\n//# sourceMappingURL=scroll-text.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst SkipForward = createLucideIcon(\"SkipForward\", [\n [\"polygon\", { points: \"5 4 15 12 5 20 5 4\", key: \"16p6eg\" }],\n [\"line\", { x1: \"19\", x2: \"19\", y1: \"5\", y2: \"19\", key: \"futhcm\" }]\n]);\n\nexport { SkipForward as default };\n//# sourceMappingURL=skip-forward.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst Trash = createLucideIcon(\"Trash\", [\n [\"path\", { d: \"M3 6h18\", key: \"d0wm0j\" }],\n [\"path\", { d: \"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6\", key: \"4alrt4\" }],\n [\"path\", { d: \"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2\", key: \"v07s0e\" }]\n]);\n\nexport { Trash as default };\n//# sourceMappingURL=trash.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst User = createLucideIcon(\"User\", [\n [\"path\", { d: \"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2\", key: \"975kel\" }],\n [\"circle\", { cx: \"12\", cy: \"7\", r: \"4\", key: \"17ys0d\" }]\n]);\n\nexport { User as default };\n//# sourceMappingURL=user.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst Volume1 = createLucideIcon(\"Volume1\", [\n [\"polygon\", { points: \"11 5 6 9 2 9 2 15 6 15 11 19 11 5\", key: \"16drj5\" }],\n [\"path\", { d: \"M15.54 8.46a5 5 0 0 1 0 7.07\", key: \"ltjumu\" }]\n]);\n\nexport { Volume1 as default };\n//# sourceMappingURL=volume-1.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst VolumeX = createLucideIcon(\"VolumeX\", [\n [\"polygon\", { points: \"11 5 6 9 2 9 2 15 6 15 11 19 11 5\", key: \"16drj5\" }],\n [\"line\", { x1: \"22\", x2: \"16\", y1: \"9\", y2: \"15\", key: \"1ewh16\" }],\n [\"line\", { x1: \"16\", x2: \"22\", y1: \"9\", y2: \"15\", key: \"5ykzw1\" }]\n]);\n\nexport { VolumeX as default };\n//# sourceMappingURL=volume-x.js.map\n","/**\n * @license lucide-react v0.359.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst X = createLucideIcon(\"X\", [\n [\"path\", { d: \"M18 6 6 18\", key: \"1bl5f8\" }],\n [\"path\", { d: \"m6 6 12 12\", key: \"d8bk6v\" }]\n]);\n\nexport { X as default };\n//# sourceMappingURL=x.js.map\n","/**\n * lodash (Custom Build) \n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \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","import { useState, useCallback, useLayoutEffect, useEffect, useRef, useMemo, useReducer } from 'react';\nimport debounce from 'lodash.debounce';\n\n// src/useBoolean/useBoolean.ts\nfunction useBoolean(defaultValue) {\n const [value, setValue] = useState(!!defaultValue);\n const setTrue = useCallback(() => {\n setValue(true);\n }, []);\n const setFalse = useCallback(() => {\n setValue(false);\n }, []);\n const toggle = useCallback(() => {\n setValue((x) => !x);\n }, []);\n return { value, setValue, setTrue, setFalse, toggle };\n}\nvar useIsomorphicLayoutEffect = typeof window !== \"undefined\" ? useLayoutEffect : useEffect;\n\n// src/useEventListener/useEventListener.ts\nfunction useEventListener(eventName, handler, element, options) {\n const savedHandler = useRef(handler);\n useIsomorphicLayoutEffect(() => {\n savedHandler.current = handler;\n }, [handler]);\n useEffect(() => {\n const targetElement = (element == null ? void 0 : element.current) ?? window;\n if (!(targetElement && targetElement.addEventListener))\n return;\n const listener = (event) => {\n savedHandler.current(event);\n };\n targetElement.addEventListener(eventName, listener, options);\n return () => {\n targetElement.removeEventListener(eventName, listener, options);\n };\n }, [eventName, element, options]);\n}\n\n// src/useClickAnyWhere/useClickAnyWhere.ts\nfunction useClickAnyWhere(handler) {\n useEventListener(\"click\", (event) => {\n handler(event);\n });\n}\nfunction useCopyToClipboard() {\n const [copiedText, setCopiedText] = useState(null);\n const copy = useCallback(async (text) => {\n if (!(navigator == null ? void 0 : navigator.clipboard)) {\n console.warn(\"Clipboard not supported\");\n return false;\n }\n try {\n await navigator.clipboard.writeText(text);\n setCopiedText(text);\n return true;\n } catch (error) {\n console.warn(\"Copy failed\", error);\n setCopiedText(null);\n return false;\n }\n }, []);\n return [copiedText, copy];\n}\nfunction useCounter(initialValue) {\n const [count, setCount] = useState(initialValue ?? 0);\n const increment = () => {\n setCount((x) => x + 1);\n };\n const decrement = () => {\n setCount((x) => x - 1);\n };\n const reset = () => {\n setCount(initialValue ?? 0);\n };\n return {\n count,\n increment,\n decrement,\n reset,\n setCount\n };\n}\nfunction useInterval(callback, delay) {\n const savedCallback = useRef(callback);\n useIsomorphicLayoutEffect(() => {\n savedCallback.current = callback;\n }, [callback]);\n useEffect(() => {\n if (delay === null) {\n return;\n }\n const id = setInterval(() => {\n savedCallback.current();\n }, delay);\n return () => {\n clearInterval(id);\n };\n }, [delay]);\n}\n\n// src/useCountdown/useCountdown.ts\nfunction useCountdown(countdownOptions) {\n let isDeprecated = false;\n let countStart, intervalMs, isIncrement, countStop;\n if (\"seconds\" in countdownOptions) {\n console.warn(\n \"[useCountdown:DEPRECATED] new interface is already available (see https://usehooks-ts.com/react-hook/use-countdown), the old version will retire on usehooks-ts@3.\"\n );\n isDeprecated = true;\n countStart = countdownOptions.seconds;\n intervalMs = countdownOptions.interval;\n isIncrement = countdownOptions.isIncrement;\n } else {\n ({ countStart, intervalMs, isIncrement, countStop } = countdownOptions);\n }\n intervalMs = intervalMs ?? 1e3;\n isIncrement = isIncrement ?? false;\n countStop = countStop ?? 0;\n const {\n count,\n increment,\n decrement,\n reset: resetCounter\n } = useCounter(countStart);\n const {\n value: isCountdownRunning,\n setTrue: startCountdown,\n setFalse: stopCountdown\n } = useBoolean(false);\n const resetCountdown = () => {\n stopCountdown();\n resetCounter();\n };\n const countdownCallback = useCallback(() => {\n if (count === countStop) {\n stopCountdown();\n return;\n }\n if (isIncrement) {\n increment();\n } else {\n decrement();\n }\n }, [count, countStop, decrement, increment, isIncrement, stopCountdown]);\n useInterval(countdownCallback, isCountdownRunning ? intervalMs : null);\n return isDeprecated ? [\n count,\n {\n start: startCountdown,\n stop: stopCountdown,\n reset: resetCountdown\n }\n ] : [\n count,\n {\n startCountdown,\n stopCountdown,\n resetCountdown\n }\n ];\n}\nfunction useEventCallback(fn) {\n const ref = useRef(() => {\n throw new Error(\"Cannot call an event handler while rendering.\");\n });\n useIsomorphicLayoutEffect(() => {\n ref.current = fn;\n }, [fn]);\n return useCallback((...args) => ref.current(...args), [ref]);\n}\n\n// src/useLocalStorage/useLocalStorage.ts\nvar IS_SERVER = typeof window === \"undefined\";\nfunction useLocalStorage(key, initialValue, options = {}) {\n const { initializeWithValue = true } = options;\n const serializer = useCallback(\n (value) => {\n if (options.serializer) {\n return options.serializer(value);\n }\n return JSON.stringify(value);\n },\n [options]\n );\n const deserializer = useCallback(\n (value) => {\n if (options.deserializer) {\n return options.deserializer(value);\n }\n if (value === \"undefined\") {\n return void 0;\n }\n const defaultValue = initialValue instanceof Function ? initialValue() : initialValue;\n let parsed;\n try {\n parsed = JSON.parse(value);\n } catch (error) {\n console.error(\"Error parsing JSON:\", error);\n return defaultValue;\n }\n return parsed;\n },\n [options, initialValue]\n );\n const readValue = useCallback(() => {\n const initialValueToUse = initialValue instanceof Function ? initialValue() : initialValue;\n if (IS_SERVER) {\n return initialValueToUse;\n }\n try {\n const raw = window.localStorage.getItem(key);\n return raw ? deserializer(raw) : initialValueToUse;\n } catch (error) {\n console.warn(`Error reading localStorage key \\u201C${key}\\u201D:`, error);\n return initialValueToUse;\n }\n }, [initialValue, key, deserializer]);\n const [storedValue, setStoredValue] = useState(() => {\n if (initializeWithValue) {\n return readValue();\n }\n return initialValue instanceof Function ? initialValue() : initialValue;\n });\n const setValue = useEventCallback((value) => {\n if (IS_SERVER) {\n console.warn(\n `Tried setting localStorage key \\u201C${key}\\u201D even though environment is not a client`\n );\n }\n try {\n const newValue = value instanceof Function ? value(readValue()) : value;\n window.localStorage.setItem(key, serializer(newValue));\n setStoredValue(newValue);\n window.dispatchEvent(new StorageEvent(\"local-storage\", { key }));\n } catch (error) {\n console.warn(`Error setting localStorage key \\u201C${key}\\u201D:`, error);\n }\n });\n useEffect(() => {\n setStoredValue(readValue());\n }, [key]);\n const handleStorageChange = useCallback(\n (event) => {\n if ((event == null ? void 0 : event.key) && event.key !== key) {\n return;\n }\n setStoredValue(readValue());\n },\n [key, readValue]\n );\n useEventListener(\"storage\", handleStorageChange);\n useEventListener(\"local-storage\", handleStorageChange);\n return [storedValue, setValue];\n}\nvar IS_SERVER2 = typeof window === \"undefined\";\nfunction useMediaQuery(query, options) {\n const defaultValue = typeof options === \"boolean\" ? options : (options == null ? void 0 : options.defaultValue) ?? false;\n const initializeWithValue = typeof options === \"boolean\" ? void 0 : (options == null ? void 0 : options.initializeWithValue) ?? void 0;\n const getMatches = (query2) => {\n if (IS_SERVER2) {\n return defaultValue;\n }\n return window.matchMedia(query2).matches;\n };\n const [matches, setMatches] = useState(() => {\n if (initializeWithValue) {\n return getMatches(query);\n }\n return defaultValue;\n });\n function handleChange() {\n setMatches(getMatches(query));\n }\n useIsomorphicLayoutEffect(() => {\n const matchMedia = window.matchMedia(query);\n handleChange();\n if (matchMedia.addListener) {\n matchMedia.addListener(handleChange);\n } else {\n matchMedia.addEventListener(\"change\", handleChange);\n }\n return () => {\n if (matchMedia.removeListener) {\n matchMedia.removeListener(handleChange);\n } else {\n matchMedia.removeEventListener(\"change\", handleChange);\n }\n };\n }, [query]);\n return matches;\n}\n\n// src/useDarkMode/useDarkMode.ts\nvar COLOR_SCHEME_QUERY = \"(prefers-color-scheme: dark)\";\nvar LOCAL_STORAGE_KEY = \"usehooks-ts-dark-mode\";\nfunction useDarkMode(options, localStorageKeyProps = LOCAL_STORAGE_KEY) {\n const counter = useRef(0);\n counter.current++;\n const defaultValue = typeof options === \"boolean\" ? options : options == null ? void 0 : options.defaultValue;\n const localStorageKey = typeof options === \"boolean\" ? localStorageKeyProps ?? LOCAL_STORAGE_KEY : (options == null ? void 0 : options.localStorageKey) ?? LOCAL_STORAGE_KEY;\n const initializeWithValue = typeof options === \"boolean\" ? void 0 : (options == null ? void 0 : options.initializeWithValue) ?? void 0;\n const isDarkOS = useMediaQuery(COLOR_SCHEME_QUERY, {\n initializeWithValue,\n defaultValue\n });\n const [isDarkMode, setDarkMode] = useLocalStorage(\n localStorageKey,\n defaultValue ?? isDarkOS ?? false,\n { initializeWithValue }\n );\n useIsomorphicLayoutEffect(() => {\n if (isDarkOS !== isDarkMode) {\n setDarkMode(isDarkOS);\n }\n }, [isDarkOS]);\n return {\n isDarkMode,\n toggle: () => {\n setDarkMode((prev) => !prev);\n },\n enable: () => {\n setDarkMode(true);\n },\n disable: () => {\n setDarkMode(false);\n },\n set: (value) => {\n setDarkMode(value);\n }\n };\n}\nfunction useDebounce(value, delay) {\n const [debouncedValue, setDebouncedValue] = useState(value);\n useEffect(() => {\n const timer = setTimeout(() => {\n setDebouncedValue(value);\n }, delay ?? 500);\n return () => {\n clearTimeout(timer);\n };\n }, [value, delay]);\n return debouncedValue;\n}\nfunction useUnmount(func) {\n const funcRef = useRef(func);\n funcRef.current = func;\n useEffect(\n () => () => {\n funcRef.current();\n },\n []\n );\n}\n\n// src/useDebounceCallback/useDebounceCallback.ts\nfunction useDebounceCallback(func, delay = 500, options) {\n const debouncedFunc = useRef();\n useUnmount(() => {\n if (debouncedFunc.current) {\n debouncedFunc.current.cancel();\n }\n });\n const debounced = useMemo(() => {\n const debouncedFuncInstance = debounce(func, delay, options);\n const wrappedFunc = (...args) => {\n return debouncedFuncInstance(...args);\n };\n wrappedFunc.cancel = () => {\n debouncedFuncInstance.cancel();\n };\n wrappedFunc.isPending = () => {\n return !!debouncedFunc.current;\n };\n wrappedFunc.flush = () => {\n return debouncedFuncInstance.flush();\n };\n return wrappedFunc;\n }, [func, delay, options]);\n useEffect(() => {\n debouncedFunc.current = debounce(func, delay, options);\n }, [func, delay, options]);\n return debounced;\n}\nfunction useDebounceValue(initialValue, delay, options) {\n const eq = (options == null ? void 0 : options.equalityFn) ?? ((left, right) => left === right);\n const unwrappedInitialValue = initialValue instanceof Function ? initialValue() : initialValue;\n const [debouncedValue, setDebouncedValue] = useState(unwrappedInitialValue);\n const previousValueRef = useRef(unwrappedInitialValue);\n const updateDebouncedValue = useDebounceCallback(\n setDebouncedValue,\n delay,\n options\n );\n if (!eq(previousValueRef.current, unwrappedInitialValue)) {\n updateDebouncedValue(unwrappedInitialValue);\n previousValueRef.current = unwrappedInitialValue;\n }\n return [debouncedValue, updateDebouncedValue];\n}\nfunction useDocumentTitle(title, options = {}) {\n const { preserveTitleOnUnmount = true } = options;\n const defaultTitle = useRef(null);\n useIsomorphicLayoutEffect(() => {\n defaultTitle.current = window.document.title;\n }, []);\n useIsomorphicLayoutEffect(() => {\n window.document.title = title;\n }, [title]);\n useUnmount(() => {\n if (!preserveTitleOnUnmount && defaultTitle.current) {\n window.document.title = defaultTitle.current;\n }\n });\n}\nfunction useEffectOnce(effect) {\n useEffect(effect, []);\n}\nfunction useElementSize(options = {}) {\n const { initializeWithValue = true } = options;\n const [ref, setRef] = useState(null);\n const readValue = useCallback(() => {\n return {\n width: (ref == null ? void 0 : ref.offsetWidth) ?? void 0,\n height: (ref == null ? void 0 : ref.offsetHeight) ?? void 0\n };\n }, [ref == null ? void 0 : ref.offsetHeight, ref == null ? void 0 : ref.offsetWidth]);\n const [size, setSize] = useState(() => {\n if (initializeWithValue) {\n return readValue();\n }\n return { width: void 0, height: void 0 };\n });\n const handleSize = useCallback(() => {\n setSize(readValue());\n }, [ref == null ? void 0 : ref.offsetHeight, ref == null ? void 0 : ref.offsetWidth]);\n useEventListener(\"resize\", handleSize);\n useIsomorphicLayoutEffect(() => {\n handleSize();\n }, [ref == null ? void 0 : ref.offsetHeight, ref == null ? void 0 : ref.offsetWidth]);\n const result = [setRef, size];\n result.ref = result[0];\n result.width = size.width;\n result.height = size.height;\n return result;\n}\nfunction useFetch(url, options) {\n const cache = useRef({});\n const cancelRequest = useRef(false);\n const initialState = {\n error: void 0,\n data: void 0\n };\n const fetchReducer = (state2, action) => {\n switch (action.type) {\n case \"loading\":\n return { ...initialState };\n case \"fetched\":\n return { ...initialState, data: action.payload };\n case \"error\":\n return { ...initialState, error: action.payload };\n default:\n return state2;\n }\n };\n const [state, dispatch] = useReducer(fetchReducer, initialState);\n useEffect(() => {\n if (!url)\n return;\n cancelRequest.current = false;\n const fetchData = async () => {\n dispatch({ type: \"loading\" });\n const currentCache = cache.current[url];\n if (currentCache) {\n dispatch({ type: \"fetched\", payload: currentCache });\n return;\n }\n try {\n const response = await fetch(url, options);\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n const data = await response.json();\n cache.current[url] = data;\n if (cancelRequest.current)\n return;\n dispatch({ type: \"fetched\", payload: data });\n } catch (error) {\n if (cancelRequest.current)\n return;\n dispatch({ type: \"error\", payload: error });\n }\n };\n void fetchData();\n return () => {\n cancelRequest.current = true;\n };\n }, [url]);\n return state;\n}\nfunction useHover(elementRef) {\n const [value, setValue] = useState(false);\n const handleMouseEnter = () => {\n setValue(true);\n };\n const handleMouseLeave = () => {\n setValue(false);\n };\n useEventListener(\"mouseenter\", handleMouseEnter, elementRef);\n useEventListener(\"mouseleave\", handleMouseLeave, elementRef);\n return value;\n}\nfunction useImageOnLoad() {\n const [isLoaded, setIsLoaded] = useState(false);\n const handleImageOnLoad = () => {\n setIsLoaded(true);\n };\n const css = {\n // Thumbnail style.\n thumbnail: {\n visibility: isLoaded ? \"hidden\" : \"visible\",\n filter: \"blur(8px)\",\n transition: \"visibility 0ms ease-out 500ms\"\n },\n // Full image style.\n fullSize: {\n opacity: isLoaded ? 1 : 0,\n transition: \"opacity 500ms ease-in 0ms\"\n }\n };\n return { handleImageOnLoad, css };\n}\nfunction useIntersectionObserver(optionsOrLegacyRef, legacyOptions) {\n var _a;\n const isLegacySignature = \"current\" in optionsOrLegacyRef;\n const options = isLegacySignature ? legacyOptions : optionsOrLegacyRef;\n const {\n threshold = 0,\n root = null,\n rootMargin = \"0%\",\n freezeOnceVisible = false,\n initialIsIntersecting = false\n } = options ?? {};\n const [newRef, setNewRef] = useState(null);\n const ref = isLegacySignature ? optionsOrLegacyRef.current : newRef;\n const [state, setState] = useState(() => ({\n isIntersecting: initialIsIntersecting,\n entry: void 0\n }));\n const callbackRef = useRef();\n callbackRef.current = options == null ? void 0 : options.onChange;\n const frozen = ((_a = state.entry) == null ? void 0 : _a.isIntersecting) && freezeOnceVisible;\n useEffect(() => {\n if (!ref)\n return;\n if (!(\"IntersectionObserver\" in window))\n return;\n if (frozen)\n return;\n let unobserve;\n const observer = new IntersectionObserver(\n (entries) => {\n const thresholds = Array.isArray(observer.thresholds) ? observer.thresholds : [observer.thresholds];\n entries.forEach((entry) => {\n const isIntersecting = entry.isIntersecting && thresholds.some((threshold2) => entry.intersectionRatio >= threshold2);\n setState({ isIntersecting, entry });\n if (callbackRef.current) {\n callbackRef.current(isIntersecting, entry);\n }\n if (isIntersecting && freezeOnceVisible && unobserve) {\n unobserve();\n unobserve = void 0;\n }\n });\n },\n { threshold, root, rootMargin }\n );\n observer.observe(ref);\n return () => {\n observer.disconnect();\n };\n }, [\n ref,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n JSON.stringify(threshold),\n root,\n rootMargin,\n frozen,\n freezeOnceVisible\n ]);\n const prevRef = useRef(null);\n useEffect(() => {\n var _a2;\n if (!ref && ((_a2 = state.entry) == null ? void 0 : _a2.target) && !freezeOnceVisible && !frozen && prevRef.current !== state.entry.target) {\n prevRef.current = state.entry.target;\n setState({ isIntersecting: initialIsIntersecting, entry: void 0 });\n }\n }, [ref, state.entry, freezeOnceVisible, frozen, initialIsIntersecting]);\n if (isLegacySignature) {\n return state.entry;\n }\n const result = [\n setNewRef,\n !!state.isIntersecting,\n state.entry\n ];\n result.ref = result[0];\n result.isIntersecting = result[1];\n result.entry = result[2];\n return result;\n}\nfunction useIsClient() {\n const [isClient, setClient] = useState(false);\n useEffect(() => {\n setClient(true);\n }, []);\n return isClient;\n}\nfunction useIsFirstRender() {\n const isFirst = useRef(true);\n if (isFirst.current) {\n isFirst.current = false;\n return true;\n }\n return isFirst.current;\n}\nfunction useIsMounted() {\n const isMounted = useRef(false);\n useEffect(() => {\n isMounted.current = true;\n return () => {\n isMounted.current = false;\n };\n }, []);\n return useCallback(() => isMounted.current, []);\n}\nfunction useLockedBody(initialLocked = false, rootId = \"___gatsby\") {\n const [locked, setLocked] = useState(initialLocked);\n useIsomorphicLayoutEffect(() => {\n if (!locked) {\n return;\n }\n const originalOverflow = document.body.style.overflow;\n const originalPaddingRight = document.body.style.paddingRight;\n document.body.style.overflow = \"hidden\";\n const root = document.getElementById(rootId);\n const scrollBarWidth = root ? root.offsetWidth - root.scrollWidth : 0;\n if (scrollBarWidth) {\n document.body.style.paddingRight = `${scrollBarWidth}px`;\n }\n return () => {\n document.body.style.overflow = originalOverflow;\n if (scrollBarWidth) {\n document.body.style.paddingRight = originalPaddingRight;\n }\n };\n }, [locked]);\n useEffect(() => {\n if (locked !== initialLocked) {\n setLocked(initialLocked);\n }\n }, [initialLocked]);\n return [locked, setLocked];\n}\nfunction useMap(initialState = /* @__PURE__ */ new Map()) {\n const [map, setMap] = useState(new Map(initialState));\n const actions = {\n set: useCallback((key, value) => {\n setMap((prev) => {\n const copy = new Map(prev);\n copy.set(key, value);\n return copy;\n });\n }, []),\n setAll: useCallback((entries) => {\n setMap(() => new Map(entries));\n }, []),\n remove: useCallback((key) => {\n setMap((prev) => {\n const copy = new Map(prev);\n copy.delete(key);\n return copy;\n });\n }, []),\n reset: useCallback(() => {\n setMap(() => /* @__PURE__ */ new Map());\n }, [])\n };\n return [map, actions];\n}\n\n// src/useOnClickOutside/useOnClickOutside.ts\nfunction useOnClickOutside(ref, handler, eventType = \"mousedown\") {\n useEventListener(eventType, (event) => {\n const target = event.target;\n if (!target || !target.isConnected) {\n return;\n }\n const isOutside = Array.isArray(ref) ? ref.every((r) => r.current && !r.current.contains(target)) : ref.current && !ref.current.contains(target);\n if (isOutside) {\n handler(event);\n }\n });\n}\nvar IS_SERVER3 = typeof window === \"undefined\";\nfunction useReadLocalStorage(key, options = {}) {\n let { initializeWithValue = true } = options;\n if (IS_SERVER3) {\n initializeWithValue = false;\n }\n const deserializer = useCallback(\n (value) => {\n if (options.deserializer) {\n return options.deserializer(value);\n }\n if (value === \"undefined\") {\n return void 0;\n }\n let parsed;\n try {\n parsed = JSON.parse(value);\n } catch (error) {\n console.error(\"Error parsing JSON:\", error);\n return null;\n }\n return parsed;\n },\n [options]\n );\n const readValue = useCallback(() => {\n if (IS_SERVER3) {\n return null;\n }\n try {\n const raw = window.localStorage.getItem(key);\n return raw ? deserializer(raw) : null;\n } catch (error) {\n console.warn(`Error reading localStorage key \\u201C${key}\\u201D:`, error);\n return null;\n }\n }, [key, deserializer]);\n const [storedValue, setStoredValue] = useState(() => {\n if (initializeWithValue) {\n return readValue();\n }\n return void 0;\n });\n useEffect(() => {\n setStoredValue(readValue());\n }, [key]);\n const handleStorageChange = useCallback(\n (event) => {\n if ((event == null ? void 0 : event.key) && event.key !== key) {\n return;\n }\n setStoredValue(readValue());\n },\n [key, readValue]\n );\n useEventListener(\"storage\", handleStorageChange);\n useEventListener(\"local-storage\", handleStorageChange);\n return storedValue;\n}\nvar initialSize = {\n width: void 0,\n height: void 0\n};\nfunction useResizeObserver(options) {\n const { ref, box = \"content-box\" } = options;\n const [{ width, height }, setSize] = useState(initialSize);\n const isMounted = useIsMounted();\n const previousSize = useRef({ ...initialSize });\n const onResize = useRef(void 0);\n onResize.current = options == null ? void 0 : options.onResize;\n useEffect(() => {\n if (!(ref == null ? void 0 : ref.current))\n return;\n if (typeof window === \"undefined\" || !(\"ResizeObserver\" in window))\n return;\n const observer = new ResizeObserver(([entry]) => {\n const boxProp = box === \"border-box\" ? \"borderBoxSize\" : box === \"device-pixel-content-box\" ? \"devicePixelContentBoxSize\" : \"contentBoxSize\";\n const newWidth = extractSize(entry, boxProp, \"inlineSize\");\n const newHeight = extractSize(entry, boxProp, \"blockSize\");\n const hasChanged = previousSize.current.width !== newWidth || previousSize.current.height !== newHeight;\n if (hasChanged) {\n const newSize = { width: newWidth, height: newHeight };\n previousSize.current.width = newWidth;\n previousSize.current.height = newHeight;\n if (onResize == null ? void 0 : onResize.current) {\n onResize.current(newSize);\n } else {\n if (isMounted()) {\n setSize(newSize);\n }\n }\n }\n });\n observer.observe(ref.current, { box });\n return () => {\n observer.disconnect();\n };\n }, [box, ref, isMounted]);\n return { width, height };\n}\nfunction extractSize(entry, box, sizeType) {\n if (!entry[box]) {\n if (box === \"contentBoxSize\") {\n return entry.contentRect[sizeType === \"inlineSize\" ? \"width\" : \"height\"];\n }\n return void 0;\n }\n return Array.isArray(entry[box]) ? entry[box][0][sizeType] : (\n // @ts-ignore Support Firefox's non-standard behavior\n entry[box][sizeType]\n );\n}\nvar IS_SERVER4 = typeof window === \"undefined\";\nfunction useScreen(options = {}) {\n let { initializeWithValue = true } = options;\n if (IS_SERVER4) {\n initializeWithValue = false;\n }\n const readScreen = () => {\n if (IS_SERVER4) {\n return void 0;\n }\n return window.screen;\n };\n const [screen, setScreen] = useState(() => {\n if (initializeWithValue) {\n return readScreen();\n }\n return void 0;\n });\n const debouncedSetScreen = useDebounceCallback(\n setScreen,\n options == null ? void 0 : options.debounceDelay\n );\n function handleSize() {\n const newScreen = readScreen();\n const setSize = (options == null ? void 0 : options.debounceDelay) ? debouncedSetScreen : setScreen;\n if (newScreen) {\n const {\n width,\n height,\n availHeight,\n availWidth,\n colorDepth,\n orientation,\n pixelDepth\n } = newScreen;\n setSize({\n width,\n height,\n availHeight,\n availWidth,\n colorDepth,\n orientation,\n pixelDepth\n });\n }\n }\n useEventListener(\"resize\", handleSize);\n useIsomorphicLayoutEffect(() => {\n handleSize();\n }, []);\n return screen;\n}\nvar cachedScriptStatuses = /* @__PURE__ */ new Map();\nfunction getScriptNode(src) {\n const node = document.querySelector(\n `script[src=\"${src}\"]`\n );\n const status = node == null ? void 0 : node.getAttribute(\"data-status\");\n return {\n node,\n status\n };\n}\nfunction useScript(src, options) {\n const [status, setStatus] = useState(() => {\n if (!src || (options == null ? void 0 : options.shouldPreventLoad)) {\n return \"idle\";\n }\n if (typeof window === \"undefined\") {\n return \"loading\";\n }\n return cachedScriptStatuses.get(src) ?? \"loading\";\n });\n useEffect(() => {\n if (!src || (options == null ? void 0 : options.shouldPreventLoad)) {\n return;\n }\n const cachedScriptStatus = cachedScriptStatuses.get(src);\n if (cachedScriptStatus === \"ready\" || cachedScriptStatus === \"error\") {\n setStatus(cachedScriptStatus);\n return;\n }\n const script = getScriptNode(src);\n let scriptNode = script.node;\n if (!scriptNode) {\n scriptNode = document.createElement(\"script\");\n scriptNode.src = src;\n scriptNode.async = true;\n scriptNode.setAttribute(\"data-status\", \"loading\");\n document.body.appendChild(scriptNode);\n const setAttributeFromEvent = (event) => {\n const scriptStatus = event.type === \"load\" ? \"ready\" : \"error\";\n scriptNode == null ? void 0 : scriptNode.setAttribute(\"data-status\", scriptStatus);\n };\n scriptNode.addEventListener(\"load\", setAttributeFromEvent);\n scriptNode.addEventListener(\"error\", setAttributeFromEvent);\n } else {\n setStatus(script.status ?? cachedScriptStatus ?? \"loading\");\n }\n const setStateFromEvent = (event) => {\n const newStatus = event.type === \"load\" ? \"ready\" : \"error\";\n setStatus(newStatus);\n cachedScriptStatuses.set(src, newStatus);\n };\n scriptNode.addEventListener(\"load\", setStateFromEvent);\n scriptNode.addEventListener(\"error\", setStateFromEvent);\n return () => {\n if (scriptNode) {\n scriptNode.removeEventListener(\"load\", setStateFromEvent);\n scriptNode.removeEventListener(\"error\", setStateFromEvent);\n }\n if (scriptNode && (options == null ? void 0 : options.removeOnUnmount)) {\n scriptNode.remove();\n cachedScriptStatuses.delete(src);\n }\n };\n }, [src, options == null ? void 0 : options.shouldPreventLoad, options == null ? void 0 : options.removeOnUnmount]);\n return status;\n}\nvar IS_SERVER5 = typeof window === \"undefined\";\nfunction useScrollLock(options = {}) {\n const { autoLock = true, lockTarget, widthReflow = true } = options;\n const target = useRef(null);\n const originalStyle = useRef(null);\n const lock = () => {\n if (target.current) {\n const { overflow, paddingRight } = window.getComputedStyle(target.current);\n originalStyle.current = { overflow, paddingRight };\n target.current.style.overflow = \"hidden\";\n if (widthReflow) {\n const scrollbarWidth = target.current.offsetWidth - target.current.scrollWidth;\n target.current.style.paddingRight = `${scrollbarWidth}px`;\n }\n }\n };\n const unlock = () => {\n if (target.current && originalStyle.current) {\n target.current.style.overflow = originalStyle.current.overflow;\n target.current.style.paddingRight = originalStyle.current.paddingRight;\n }\n };\n useLayoutEffect(() => {\n if (IS_SERVER5)\n return;\n if (lockTarget) {\n target.current = typeof lockTarget === \"string\" ? document.querySelector(lockTarget) : lockTarget;\n }\n if (!target.current) {\n target.current = document.body;\n }\n if (autoLock) {\n lock();\n }\n return () => {\n unlock();\n };\n }, [autoLock, lockTarget, widthReflow]);\n return { lock, unlock };\n}\nvar IS_SERVER6 = typeof window === \"undefined\";\nfunction useSessionStorage(key, initialValue, options = {}) {\n const { initializeWithValue = true } = options;\n const serializer = useCallback(\n (value) => {\n if (options.serializer) {\n return options.serializer(value);\n }\n return JSON.stringify(value);\n },\n [options]\n );\n const deserializer = useCallback(\n (value) => {\n if (options.deserializer) {\n return options.deserializer(value);\n }\n if (value === \"undefined\") {\n return void 0;\n }\n const defaultValue = initialValue instanceof Function ? initialValue() : initialValue;\n let parsed;\n try {\n parsed = JSON.parse(value);\n } catch (error) {\n console.error(\"Error parsing JSON:\", error);\n return defaultValue;\n }\n return parsed;\n },\n [options, initialValue]\n );\n const readValue = useCallback(() => {\n const initialValueToUse = initialValue instanceof Function ? initialValue() : initialValue;\n if (IS_SERVER6) {\n return initialValueToUse;\n }\n try {\n const raw = window.sessionStorage.getItem(key);\n return raw ? deserializer(raw) : initialValueToUse;\n } catch (error) {\n console.warn(`Error reading sessionStorage key \\u201C${key}\\u201D:`, error);\n return initialValueToUse;\n }\n }, [initialValue, key, deserializer]);\n const [storedValue, setStoredValue] = useState(() => {\n if (initializeWithValue) {\n return readValue();\n }\n return initialValue instanceof Function ? initialValue() : initialValue;\n });\n const setValue = useEventCallback((value) => {\n if (IS_SERVER6) {\n console.warn(\n `Tried setting sessionStorage key \\u201C${key}\\u201D even though environment is not a client`\n );\n }\n try {\n const newValue = value instanceof Function ? value(readValue()) : value;\n window.sessionStorage.setItem(key, serializer(newValue));\n setStoredValue(newValue);\n window.dispatchEvent(new StorageEvent(\"session-storage\", { key }));\n } catch (error) {\n console.warn(`Error setting sessionStorage key \\u201C${key}\\u201D:`, error);\n }\n });\n useEffect(() => {\n setStoredValue(readValue());\n }, [key]);\n const handleStorageChange = useCallback(\n (event) => {\n if ((event == null ? void 0 : event.key) && event.key !== key) {\n return;\n }\n setStoredValue(readValue());\n },\n [key, readValue]\n );\n useEventListener(\"storage\", handleStorageChange);\n useEventListener(\"session-storage\", handleStorageChange);\n return [storedValue, setValue];\n}\n\n// src/useSsr/useSsr.ts\nfunction useSsr() {\n var _a;\n const isDOM = (\n // eslint-disable-next-line @typescript-eslint/prefer-optional-chain\n typeof window !== \"undefined\" && !!((_a = window == null ? void 0 : window.document) == null ? void 0 : _a.documentElement)\n );\n return {\n isBrowser: isDOM,\n isServer: !isDOM\n };\n}\nfunction useStep(maxStep) {\n const [currentStep, setCurrentStep] = useState(1);\n const canGoToNextStep = currentStep + 1 <= maxStep;\n const canGoToPrevStep = currentStep - 1 > 0;\n const setStep = useCallback(\n (step) => {\n const newStep = step instanceof Function ? step(currentStep) : step;\n if (newStep >= 1 && newStep <= maxStep) {\n setCurrentStep(newStep);\n return;\n }\n throw new Error(\"Step not valid\");\n },\n [maxStep, currentStep]\n );\n const goToNextStep = useCallback(() => {\n if (canGoToNextStep) {\n setCurrentStep((step) => step + 1);\n }\n }, [canGoToNextStep]);\n const goToPrevStep = useCallback(() => {\n if (canGoToPrevStep) {\n setCurrentStep((step) => step - 1);\n }\n }, [canGoToPrevStep]);\n const reset = useCallback(() => {\n setCurrentStep(1);\n }, []);\n return [\n currentStep,\n {\n goToNextStep,\n goToPrevStep,\n canGoToNextStep,\n canGoToPrevStep,\n setStep,\n reset\n }\n ];\n}\n\n// src/useTernaryDarkMode/useTernaryDarkMode.ts\nvar COLOR_SCHEME_QUERY2 = \"(prefers-color-scheme: dark)\";\nvar LOCAL_STORAGE_KEY2 = \"usehooks-ts-ternary-dark-mode\";\nfunction useTernaryDarkMode(options) {\n const defaultValue = typeof options === \"string\" ? \"system\" : (options == null ? void 0 : options.defaultValue) ?? \"system\";\n const localStorageKey = typeof options === \"string\" ? options : (options == null ? void 0 : options.localStorageKey) ?? LOCAL_STORAGE_KEY2;\n const initializeWithValue = typeof options === \"string\" ? void 0 : (options == null ? void 0 : options.initializeWithValue) ?? void 0;\n const isDarkOS = useMediaQuery(COLOR_SCHEME_QUERY2, { initializeWithValue });\n const [mode, setMode] = useLocalStorage(localStorageKey, defaultValue, {\n initializeWithValue\n });\n const isDarkMode = mode === \"dark\" || mode === \"system\" && isDarkOS;\n const toggleTernaryDarkMode = () => {\n const modes = [\"light\", \"system\", \"dark\"];\n setMode((prevMode) => {\n const nextIndex = (modes.indexOf(prevMode) + 1) % modes.length;\n return modes[nextIndex];\n });\n };\n return {\n isDarkMode,\n ternaryDarkMode: mode,\n setTernaryDarkMode: setMode,\n toggleTernaryDarkMode\n };\n}\nfunction useTimeout(callback, delay) {\n const savedCallback = useRef(callback);\n useIsomorphicLayoutEffect(() => {\n savedCallback.current = callback;\n }, [callback]);\n useEffect(() => {\n if (!delay && delay !== 0) {\n return;\n }\n const id = setTimeout(() => {\n savedCallback.current();\n }, delay);\n return () => {\n clearTimeout(id);\n };\n }, [delay]);\n}\nfunction useToggle(defaultValue) {\n const [value, setValue] = useState(!!defaultValue);\n const toggle = useCallback(() => {\n setValue((x) => !x);\n }, []);\n return [value, toggle, setValue];\n}\nfunction useUpdateEffect(effect, deps) {\n const isFirst = useIsFirstRender();\n useEffect(() => {\n if (!isFirst) {\n return effect();\n }\n }, deps);\n}\nvar IS_SERVER7 = typeof window === \"undefined\";\nfunction useWindowSize(options = {}) {\n let { initializeWithValue = true } = options;\n if (IS_SERVER7) {\n initializeWithValue = false;\n }\n const [windowSize, setWindowSize] = useState(() => {\n if (initializeWithValue) {\n return {\n width: window.innerWidth,\n height: window.innerHeight\n };\n }\n return {\n width: void 0,\n height: void 0\n };\n });\n const debouncedSetWindowSize = useDebounceCallback(\n setWindowSize,\n options == null ? void 0 : options.debounceDelay\n );\n function handleSize() {\n const setSize = (options == null ? void 0 : options.debounceDelay) ? debouncedSetWindowSize : setWindowSize;\n setSize({\n width: window.innerWidth,\n height: window.innerHeight\n });\n }\n useEventListener(\"resize\", handleSize);\n useIsomorphicLayoutEffect(() => {\n handleSize();\n }, []);\n return windowSize;\n}\n\nexport { useBoolean, useClickAnyWhere, useCopyToClipboard, useCountdown, useCounter, useDarkMode, useDebounce, useDebounceCallback, useDebounceValue, useDocumentTitle, useEffectOnce, useElementSize, useEventCallback, useEventListener, useFetch, useHover, useImageOnLoad, useIntersectionObserver, useInterval, useIsClient, useIsFirstRender, useIsMounted, useIsomorphicLayoutEffect, useLocalStorage, useLockedBody, useMap, useMediaQuery, useOnClickOutside, useReadLocalStorage, useResizeObserver, useScreen, useScript, useScrollLock, useSessionStorage, useSsr, useStep, useTernaryDarkMode, useTimeout, useToggle, useUnmount, useUpdateEffect, useWindowSize };\n","function getNodeName(node) {\n if (isNode(node)) {\n return (node.nodeName || '').toLowerCase();\n }\n // Mocked nodes in testing environments may not be instances of Node. By\n // returning `#document` an infinite loop won't occur.\n // https://github.com/floating-ui/floating-ui/issues/2317\n return '#document';\n}\nfunction getWindow(node) {\n var _node$ownerDocument;\n return (node == null ? void 0 : (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;\n}\nfunction getDocumentElement(node) {\n var _ref;\n return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;\n}\nfunction isNode(value) {\n return value instanceof Node || value instanceof getWindow(value).Node;\n}\nfunction isElement(value) {\n return value instanceof Element || value instanceof getWindow(value).Element;\n}\nfunction isHTMLElement(value) {\n return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;\n}\nfunction isShadowRoot(value) {\n // Browsers without `ShadowRoot` support.\n if (typeof ShadowRoot === 'undefined') {\n return false;\n }\n return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;\n}\nfunction isOverflowElement(element) {\n const {\n overflow,\n overflowX,\n overflowY,\n display\n } = getComputedStyle(element);\n return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !['inline', 'contents'].includes(display);\n}\nfunction isTableElement(element) {\n return ['table', 'td', 'th'].includes(getNodeName(element));\n}\nfunction isContainingBlock(element) {\n const webkit = isWebKit();\n const css = getComputedStyle(element);\n\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n return css.transform !== 'none' || css.perspective !== 'none' || (css.containerType ? css.containerType !== 'normal' : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== 'none' : false) || !webkit && (css.filter ? css.filter !== 'none' : false) || ['transform', 'perspective', 'filter'].some(value => (css.willChange || '').includes(value)) || ['paint', 'layout', 'strict', 'content'].some(value => (css.contain || '').includes(value));\n}\nfunction getContainingBlock(element) {\n let currentNode = getParentNode(element);\n while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {\n if (isContainingBlock(currentNode)) {\n return currentNode;\n } else {\n currentNode = getParentNode(currentNode);\n }\n }\n return null;\n}\nfunction isWebKit() {\n if (typeof CSS === 'undefined' || !CSS.supports) return false;\n return CSS.supports('-webkit-backdrop-filter', 'none');\n}\nfunction isLastTraversableNode(node) {\n return ['html', 'body', '#document'].includes(getNodeName(node));\n}\nfunction getComputedStyle(element) {\n return getWindow(element).getComputedStyle(element);\n}\nfunction getNodeScroll(element) {\n if (isElement(element)) {\n return {\n scrollLeft: element.scrollLeft,\n scrollTop: element.scrollTop\n };\n }\n return {\n scrollLeft: element.pageXOffset,\n scrollTop: element.pageYOffset\n };\n}\nfunction getParentNode(node) {\n if (getNodeName(node) === 'html') {\n return node;\n }\n const result =\n // Step into the shadow DOM of the parent of a slotted node.\n node.assignedSlot ||\n // DOM Element detected.\n node.parentNode ||\n // ShadowRoot detected.\n isShadowRoot(node) && node.host ||\n // Fallback.\n getDocumentElement(node);\n return isShadowRoot(result) ? result.host : result;\n}\nfunction getNearestOverflowAncestor(node) {\n const parentNode = getParentNode(node);\n if (isLastTraversableNode(parentNode)) {\n return node.ownerDocument ? node.ownerDocument.body : node.body;\n }\n if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {\n return parentNode;\n }\n return getNearestOverflowAncestor(parentNode);\n}\nfunction getOverflowAncestors(node, list, traverseIframes) {\n var _node$ownerDocument2;\n if (list === void 0) {\n list = [];\n }\n if (traverseIframes === void 0) {\n traverseIframes = true;\n }\n const scrollableAncestor = getNearestOverflowAncestor(node);\n const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);\n const win = getWindow(scrollableAncestor);\n if (isBody) {\n return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], win.frameElement && traverseIframes ? getOverflowAncestors(win.frameElement) : []);\n }\n return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));\n}\n\nexport { getComputedStyle, getContainingBlock, getDocumentElement, getNearestOverflowAncestor, getNodeName, getNodeScroll, getOverflowAncestors, getParentNode, getWindow, isContainingBlock, isElement, isHTMLElement, isLastTraversableNode, isNode, isOverflowElement, isShadowRoot, isTableElement, isWebKit };\n","import { isShadowRoot, isHTMLElement } from '@floating-ui/utils/dom';\n\nfunction activeElement(doc) {\n let activeElement = doc.activeElement;\n while (((_activeElement = activeElement) == null || (_activeElement = _activeElement.shadowRoot) == null ? void 0 : _activeElement.activeElement) != null) {\n var _activeElement;\n activeElement = activeElement.shadowRoot.activeElement;\n }\n return activeElement;\n}\nfunction contains(parent, child) {\n if (!parent || !child) {\n return false;\n }\n const rootNode = child.getRootNode && child.getRootNode();\n\n // First, attempt with faster native method\n if (parent.contains(child)) {\n return true;\n }\n\n // then fallback to custom implementation with Shadow DOM support\n if (rootNode && isShadowRoot(rootNode)) {\n let next = child;\n while (next) {\n if (parent === next) {\n return true;\n }\n // @ts-ignore\n next = next.parentNode || next.host;\n }\n }\n\n // Give up, the result is false\n return false;\n}\n// Avoid Chrome DevTools blue warning.\nfunction getPlatform() {\n const uaData = navigator.userAgentData;\n if (uaData != null && uaData.platform) {\n return uaData.platform;\n }\n return navigator.platform;\n}\nfunction getUserAgent() {\n const uaData = navigator.userAgentData;\n if (uaData && Array.isArray(uaData.brands)) {\n return uaData.brands.map(_ref => {\n let {\n brand,\n version\n } = _ref;\n return brand + \"/\" + version;\n }).join(' ');\n }\n return navigator.userAgent;\n}\n\n// License: https://github.com/adobe/react-spectrum/blob/b35d5c02fe900badccd0cf1a8f23bb593419f238/packages/@react-aria/utils/src/isVirtualEvent.ts\nfunction isVirtualClick(event) {\n // FIXME: Firefox is now emitting a deprecation warning for `mozInputSource`.\n // Try to find a workaround for this. `react-aria` source still has the check.\n if (event.mozInputSource === 0 && event.isTrusted) {\n return true;\n }\n if (isAndroid() && event.pointerType) {\n return event.type === 'click' && event.buttons === 1;\n }\n return event.detail === 0 && !event.pointerType;\n}\nfunction isVirtualPointerEvent(event) {\n return !isAndroid() && event.width === 0 && event.height === 0 || event.width === 1 && event.height === 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'mouse' ||\n // iOS VoiceOver returns 0.333• for width/height.\n event.width < 1 && event.height < 1 && event.pressure === 0 && event.detail === 0;\n}\nfunction isSafari() {\n // Chrome DevTools does not complain about navigator.vendor\n return /apple/i.test(navigator.vendor);\n}\nfunction isAndroid() {\n const re = /android/i;\n return re.test(getPlatform()) || re.test(getUserAgent());\n}\nfunction isMac() {\n return getPlatform().toLowerCase().startsWith('mac') && !navigator.maxTouchPoints;\n}\nfunction isMouseLikePointerType(pointerType, strict) {\n // On some Linux machines with Chromium, mouse inputs return a `pointerType`\n // of \"pen\": https://github.com/floating-ui/floating-ui/issues/2015\n const values = ['mouse', 'pen'];\n if (!strict) {\n values.push('', undefined);\n }\n return values.includes(pointerType);\n}\nfunction isReactEvent(event) {\n return 'nativeEvent' in event;\n}\nfunction isRootElement(element) {\n return element.matches('html,body');\n}\nfunction getDocument(node) {\n return (node == null ? void 0 : node.ownerDocument) || document;\n}\nfunction isEventTargetWithin(event, node) {\n if (node == null) {\n return false;\n }\n if ('composedPath' in event) {\n return event.composedPath().includes(node);\n }\n\n // TS thinks `event` is of type never as it assumes all browsers support composedPath, but browsers without shadow dom don't\n const e = event;\n return e.target != null && node.contains(e.target);\n}\nfunction getTarget(event) {\n if ('composedPath' in event) {\n return event.composedPath()[0];\n }\n\n // TS thinks `event` is of type never as it assumes all browsers support\n // `composedPath()`, but browsers without shadow DOM don't.\n return event.target;\n}\nconst TYPEABLE_SELECTOR = \"input:not([type='hidden']):not([disabled]),\" + \"[contenteditable]:not([contenteditable='false']),textarea:not([disabled])\";\nfunction isTypeableElement(element) {\n return isHTMLElement(element) && element.matches(TYPEABLE_SELECTOR);\n}\nfunction stopEvent(event) {\n event.preventDefault();\n event.stopPropagation();\n}\nfunction isTypeableCombobox(element) {\n if (!element) return false;\n return element.getAttribute('role') === 'combobox' && isTypeableElement(element);\n}\n\nexport { TYPEABLE_SELECTOR, activeElement, contains, getDocument, getPlatform, getTarget, getUserAgent, isAndroid, isEventTargetWithin, isMac, isMouseLikePointerType, isReactEvent, isRootElement, isSafari, isTypeableCombobox, isTypeableElement, isVirtualClick, isVirtualPointerEvent, stopEvent };\n","const sides = ['top', 'right', 'bottom', 'left'];\nconst alignments = ['start', 'end'];\nconst placements = /*#__PURE__*/sides.reduce((acc, side) => acc.concat(side, side + \"-\" + alignments[0], side + \"-\" + alignments[1]), []);\nconst min = Math.min;\nconst max = Math.max;\nconst round = Math.round;\nconst floor = Math.floor;\nconst createCoords = v => ({\n x: v,\n y: v\n});\nconst oppositeSideMap = {\n left: 'right',\n right: 'left',\n bottom: 'top',\n top: 'bottom'\n};\nconst oppositeAlignmentMap = {\n start: 'end',\n end: 'start'\n};\nfunction clamp(start, value, end) {\n return max(start, min(value, end));\n}\nfunction evaluate(value, param) {\n return typeof value === 'function' ? value(param) : value;\n}\nfunction getSide(placement) {\n return placement.split('-')[0];\n}\nfunction getAlignment(placement) {\n return placement.split('-')[1];\n}\nfunction getOppositeAxis(axis) {\n return axis === 'x' ? 'y' : 'x';\n}\nfunction getAxisLength(axis) {\n return axis === 'y' ? 'height' : 'width';\n}\nfunction getSideAxis(placement) {\n return ['top', 'bottom'].includes(getSide(placement)) ? 'y' : 'x';\n}\nfunction getAlignmentAxis(placement) {\n return getOppositeAxis(getSideAxis(placement));\n}\nfunction getAlignmentSides(placement, rects, rtl) {\n if (rtl === void 0) {\n rtl = false;\n }\n const alignment = getAlignment(placement);\n const alignmentAxis = getAlignmentAxis(placement);\n const length = getAxisLength(alignmentAxis);\n let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top';\n if (rects.reference[length] > rects.floating[length]) {\n mainAlignmentSide = getOppositePlacement(mainAlignmentSide);\n }\n return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];\n}\nfunction getExpandedPlacements(placement) {\n const oppositePlacement = getOppositePlacement(placement);\n return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];\n}\nfunction getOppositeAlignmentPlacement(placement) {\n return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]);\n}\nfunction getSideList(side, isStart, rtl) {\n const lr = ['left', 'right'];\n const rl = ['right', 'left'];\n const tb = ['top', 'bottom'];\n const bt = ['bottom', 'top'];\n switch (side) {\n case 'top':\n case 'bottom':\n if (rtl) return isStart ? rl : lr;\n return isStart ? lr : rl;\n case 'left':\n case 'right':\n return isStart ? tb : bt;\n default:\n return [];\n }\n}\nfunction getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {\n const alignment = getAlignment(placement);\n let list = getSideList(getSide(placement), direction === 'start', rtl);\n if (alignment) {\n list = list.map(side => side + \"-\" + alignment);\n if (flipAlignment) {\n list = list.concat(list.map(getOppositeAlignmentPlacement));\n }\n }\n return list;\n}\nfunction getOppositePlacement(placement) {\n return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]);\n}\nfunction expandPaddingObject(padding) {\n return {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0,\n ...padding\n };\n}\nfunction getPaddingObject(padding) {\n return typeof padding !== 'number' ? expandPaddingObject(padding) : {\n top: padding,\n right: padding,\n bottom: padding,\n left: padding\n };\n}\nfunction rectToClientRect(rect) {\n return {\n ...rect,\n top: rect.y,\n left: rect.x,\n right: rect.x + rect.width,\n bottom: rect.y + rect.height\n };\n}\n\nexport { alignments, clamp, createCoords, evaluate, expandPaddingObject, floor, getAlignment, getAlignmentAxis, getAlignmentSides, getAxisLength, getExpandedPlacements, getOppositeAlignmentPlacement, getOppositeAxis, getOppositeAxisPlacements, getOppositePlacement, getPaddingObject, getSide, getSideAxis, max, min, placements, rectToClientRect, round, sides };\n","import { getSideAxis, getAlignmentAxis, getAxisLength, getSide, getAlignment, evaluate, getPaddingObject, rectToClientRect, min, clamp, placements, getAlignmentSides, getOppositeAlignmentPlacement, getOppositePlacement, getExpandedPlacements, getOppositeAxisPlacements, sides, max, getOppositeAxis } from '@floating-ui/utils';\nexport { rectToClientRect } from '@floating-ui/utils';\n\nfunction computeCoordsFromPlacement(_ref, placement, rtl) {\n let {\n reference,\n floating\n } = _ref;\n const sideAxis = getSideAxis(placement);\n const alignmentAxis = getAlignmentAxis(placement);\n const alignLength = getAxisLength(alignmentAxis);\n const side = getSide(placement);\n const isVertical = sideAxis === 'y';\n const commonX = reference.x + reference.width / 2 - floating.width / 2;\n const commonY = reference.y + reference.height / 2 - floating.height / 2;\n const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;\n let coords;\n switch (side) {\n case 'top':\n coords = {\n x: commonX,\n y: reference.y - floating.height\n };\n break;\n case 'bottom':\n coords = {\n x: commonX,\n y: reference.y + reference.height\n };\n break;\n case 'right':\n coords = {\n x: reference.x + reference.width,\n y: commonY\n };\n break;\n case 'left':\n coords = {\n x: reference.x - floating.width,\n y: commonY\n };\n break;\n default:\n coords = {\n x: reference.x,\n y: reference.y\n };\n }\n switch (getAlignment(placement)) {\n case 'start':\n coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);\n break;\n case 'end':\n coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);\n break;\n }\n return coords;\n}\n\n/**\n * Computes the `x` and `y` coordinates that will place the floating element\n * next to a reference element when it is given a certain positioning strategy.\n *\n * This export does not have any `platform` interface logic. You will need to\n * write one for the platform you are using Floating UI with.\n */\nconst computePosition = async (reference, floating, config) => {\n const {\n placement = 'bottom',\n strategy = 'absolute',\n middleware = [],\n platform\n } = config;\n const validMiddleware = middleware.filter(Boolean);\n const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating));\n let rects = await platform.getElementRects({\n reference,\n floating,\n strategy\n });\n let {\n x,\n y\n } = computeCoordsFromPlacement(rects, placement, rtl);\n let statefulPlacement = placement;\n let middlewareData = {};\n let resetCount = 0;\n for (let i = 0; i < validMiddleware.length; i++) {\n const {\n name,\n fn\n } = validMiddleware[i];\n const {\n x: nextX,\n y: nextY,\n data,\n reset\n } = await fn({\n x,\n y,\n initialPlacement: placement,\n placement: statefulPlacement,\n strategy,\n middlewareData,\n rects,\n platform,\n elements: {\n reference,\n floating\n }\n });\n x = nextX != null ? nextX : x;\n y = nextY != null ? nextY : y;\n middlewareData = {\n ...middlewareData,\n [name]: {\n ...middlewareData[name],\n ...data\n }\n };\n if (reset && resetCount <= 50) {\n resetCount++;\n if (typeof reset === 'object') {\n if (reset.placement) {\n statefulPlacement = reset.placement;\n }\n if (reset.rects) {\n rects = reset.rects === true ? await platform.getElementRects({\n reference,\n floating,\n strategy\n }) : reset.rects;\n }\n ({\n x,\n y\n } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));\n }\n i = -1;\n continue;\n }\n }\n return {\n x,\n y,\n placement: statefulPlacement,\n strategy,\n middlewareData\n };\n};\n\n/**\n * Resolves with an object of overflow side offsets that determine how much the\n * element is overflowing a given clipping boundary on each side.\n * - positive = overflowing the boundary by that number of pixels\n * - negative = how many pixels left before it will overflow\n * - 0 = lies flush with the boundary\n * @see https://floating-ui.com/docs/detectOverflow\n */\nasync function detectOverflow(state, options) {\n var _await$platform$isEle;\n if (options === void 0) {\n options = {};\n }\n const {\n x,\n y,\n platform,\n rects,\n elements,\n strategy\n } = state;\n const {\n boundary = 'clippingAncestors',\n rootBoundary = 'viewport',\n elementContext = 'floating',\n altBoundary = false,\n padding = 0\n } = evaluate(options, state);\n const paddingObject = getPaddingObject(padding);\n const altContext = elementContext === 'floating' ? 'reference' : 'floating';\n const element = elements[altBoundary ? altContext : elementContext];\n const clippingClientRect = rectToClientRect(await platform.getClippingRect({\n element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))),\n boundary,\n rootBoundary,\n strategy\n }));\n const rect = elementContext === 'floating' ? {\n ...rects.floating,\n x,\n y\n } : rects.reference;\n const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating));\n const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || {\n x: 1,\n y: 1\n } : {\n x: 1,\n y: 1\n };\n const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({\n rect,\n offsetParent,\n strategy\n }) : rect);\n return {\n top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,\n bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,\n left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,\n right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x\n };\n}\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = options => ({\n name: 'arrow',\n options,\n async fn(state) {\n const {\n x,\n y,\n placement,\n rects,\n platform,\n elements,\n middlewareData\n } = state;\n // Since `element` is required, we don't Partial<> the type.\n const {\n element,\n padding = 0\n } = evaluate(options, state) || {};\n if (element == null) {\n return {};\n }\n const paddingObject = getPaddingObject(padding);\n const coords = {\n x,\n y\n };\n const axis = getAlignmentAxis(placement);\n const length = getAxisLength(axis);\n const arrowDimensions = await platform.getDimensions(element);\n const isYAxis = axis === 'y';\n const minProp = isYAxis ? 'top' : 'left';\n const maxProp = isYAxis ? 'bottom' : 'right';\n const clientProp = isYAxis ? 'clientHeight' : 'clientWidth';\n const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];\n const startDiff = coords[axis] - rects.reference[axis];\n const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element));\n let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0;\n\n // DOM platform can return `window` as the `offsetParent`.\n if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) {\n clientSize = elements.floating[clientProp] || rects.floating[length];\n }\n const centerToReference = endDiff / 2 - startDiff / 2;\n\n // If the padding is large enough that it causes the arrow to no longer be\n // centered, modify the padding so that it is centered.\n const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;\n const minPadding = min(paddingObject[minProp], largestPossiblePadding);\n const maxPadding = min(paddingObject[maxProp], largestPossiblePadding);\n\n // Make sure the arrow doesn't overflow the floating element if the center\n // point is outside the floating element's bounds.\n const min$1 = minPadding;\n const max = clientSize - arrowDimensions[length] - maxPadding;\n const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;\n const offset = clamp(min$1, center, max);\n\n // If the reference is small enough that the arrow's padding causes it to\n // to point to nothing for an aligned placement, adjust the offset of the\n // floating element itself. To ensure `shift()` continues to take action,\n // a single reset is performed when this is true.\n const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center != offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;\n const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0;\n return {\n [axis]: coords[axis] + alignmentOffset,\n data: {\n [axis]: offset,\n centerOffset: center - offset - alignmentOffset,\n ...(shouldAddOffset && {\n alignmentOffset\n })\n },\n reset: shouldAddOffset\n };\n }\n});\n\nfunction getPlacementList(alignment, autoAlignment, allowedPlacements) {\n const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement);\n return allowedPlacementsSortedByAlignment.filter(placement => {\n if (alignment) {\n return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false);\n }\n return true;\n });\n}\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'autoPlacement',\n options,\n async fn(state) {\n var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE;\n const {\n rects,\n middlewareData,\n placement,\n platform,\n elements\n } = state;\n const {\n crossAxis = false,\n alignment,\n allowedPlacements = placements,\n autoAlignment = true,\n ...detectOverflowOptions\n } = evaluate(options, state);\n const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements;\n const overflow = await detectOverflow(state, detectOverflowOptions);\n const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0;\n const currentPlacement = placements$1[currentIndex];\n if (currentPlacement == null) {\n return {};\n }\n const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)));\n\n // Make `computeCoords` start from the right place.\n if (placement !== currentPlacement) {\n return {\n reset: {\n placement: placements$1[0]\n }\n };\n }\n const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]];\n const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), {\n placement: currentPlacement,\n overflows: currentOverflows\n }];\n const nextPlacement = placements$1[currentIndex + 1];\n\n // There are more placements to check.\n if (nextPlacement) {\n return {\n data: {\n index: currentIndex + 1,\n overflows: allOverflows\n },\n reset: {\n placement: nextPlacement\n }\n };\n }\n const placementsSortedByMostSpace = allOverflows.map(d => {\n const alignment = getAlignment(d.placement);\n return [d.placement, alignment && crossAxis ?\n // Check along the mainAxis and main crossAxis side.\n d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) :\n // Check only the mainAxis.\n d.overflows[0], d.overflows];\n }).sort((a, b) => a[1] - b[1]);\n const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0,\n // Aligned placements should not check their opposite crossAxis\n // side.\n getAlignment(d[0]) ? 2 : 3).every(v => v <= 0));\n const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0];\n if (resetPlacement !== placement) {\n return {\n data: {\n index: currentIndex + 1,\n overflows: allOverflows\n },\n reset: {\n placement: resetPlacement\n }\n };\n }\n return {};\n }\n };\n};\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'flip',\n options,\n async fn(state) {\n var _middlewareData$arrow, _middlewareData$flip;\n const {\n placement,\n middlewareData,\n rects,\n initialPlacement,\n platform,\n elements\n } = state;\n const {\n mainAxis: checkMainAxis = true,\n crossAxis: checkCrossAxis = true,\n fallbackPlacements: specifiedFallbackPlacements,\n fallbackStrategy = 'bestFit',\n fallbackAxisSideDirection = 'none',\n flipAlignment = true,\n ...detectOverflowOptions\n } = evaluate(options, state);\n\n // If a reset by the arrow was caused due to an alignment offset being\n // added, we should skip any logic now since `flip()` has already done its\n // work.\n // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643\n if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {\n return {};\n }\n const side = getSide(placement);\n const isBasePlacement = getSide(initialPlacement) === initialPlacement;\n const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));\n const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));\n if (!specifiedFallbackPlacements && fallbackAxisSideDirection !== 'none') {\n fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));\n }\n const placements = [initialPlacement, ...fallbackPlacements];\n const overflow = await detectOverflow(state, detectOverflowOptions);\n const overflows = [];\n let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];\n if (checkMainAxis) {\n overflows.push(overflow[side]);\n }\n if (checkCrossAxis) {\n const sides = getAlignmentSides(placement, rects, rtl);\n overflows.push(overflow[sides[0]], overflow[sides[1]]);\n }\n overflowsData = [...overflowsData, {\n placement,\n overflows\n }];\n\n // One or more sides is overflowing.\n if (!overflows.every(side => side <= 0)) {\n var _middlewareData$flip2, _overflowsData$filter;\n const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;\n const nextPlacement = placements[nextIndex];\n if (nextPlacement) {\n // Try next placement and re-run the lifecycle.\n return {\n data: {\n index: nextIndex,\n overflows: overflowsData\n },\n reset: {\n placement: nextPlacement\n }\n };\n }\n\n // First, find the candidates that fit on the mainAxis side of overflow,\n // then find the placement that fits the best on the main crossAxis side.\n let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;\n\n // Otherwise fallback.\n if (!resetPlacement) {\n switch (fallbackStrategy) {\n case 'bestFit':\n {\n var _overflowsData$map$so;\n const placement = (_overflowsData$map$so = overflowsData.map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$map$so[0];\n if (placement) {\n resetPlacement = placement;\n }\n break;\n }\n case 'initialPlacement':\n resetPlacement = initialPlacement;\n break;\n }\n }\n if (placement !== resetPlacement) {\n return {\n reset: {\n placement: resetPlacement\n }\n };\n }\n }\n return {};\n }\n };\n};\n\nfunction getSideOffsets(overflow, rect) {\n return {\n top: overflow.top - rect.height,\n right: overflow.right - rect.width,\n bottom: overflow.bottom - rect.height,\n left: overflow.left - rect.width\n };\n}\nfunction isAnySideFullyClipped(overflow) {\n return sides.some(side => overflow[side] >= 0);\n}\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'hide',\n options,\n async fn(state) {\n const {\n rects\n } = state;\n const {\n strategy = 'referenceHidden',\n ...detectOverflowOptions\n } = evaluate(options, state);\n switch (strategy) {\n case 'referenceHidden':\n {\n const overflow = await detectOverflow(state, {\n ...detectOverflowOptions,\n elementContext: 'reference'\n });\n const offsets = getSideOffsets(overflow, rects.reference);\n return {\n data: {\n referenceHiddenOffsets: offsets,\n referenceHidden: isAnySideFullyClipped(offsets)\n }\n };\n }\n case 'escaped':\n {\n const overflow = await detectOverflow(state, {\n ...detectOverflowOptions,\n altBoundary: true\n });\n const offsets = getSideOffsets(overflow, rects.floating);\n return {\n data: {\n escapedOffsets: offsets,\n escaped: isAnySideFullyClipped(offsets)\n }\n };\n }\n default:\n {\n return {};\n }\n }\n }\n };\n};\n\nfunction getBoundingRect(rects) {\n const minX = min(...rects.map(rect => rect.left));\n const minY = min(...rects.map(rect => rect.top));\n const maxX = max(...rects.map(rect => rect.right));\n const maxY = max(...rects.map(rect => rect.bottom));\n return {\n x: minX,\n y: minY,\n width: maxX - minX,\n height: maxY - minY\n };\n}\nfunction getRectsByLine(rects) {\n const sortedRects = rects.slice().sort((a, b) => a.y - b.y);\n const groups = [];\n let prevRect = null;\n for (let i = 0; i < sortedRects.length; i++) {\n const rect = sortedRects[i];\n if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) {\n groups.push([rect]);\n } else {\n groups[groups.length - 1].push(rect);\n }\n prevRect = rect;\n }\n return groups.map(rect => rectToClientRect(getBoundingRect(rect)));\n}\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'inline',\n options,\n async fn(state) {\n const {\n placement,\n elements,\n rects,\n platform,\n strategy\n } = state;\n // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a\n // ClientRect's bounds, despite the event listener being triggered. A\n // padding of 2 seems to handle this issue.\n const {\n padding = 2,\n x,\n y\n } = evaluate(options, state);\n const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []);\n const clientRects = getRectsByLine(nativeClientRects);\n const fallback = rectToClientRect(getBoundingRect(nativeClientRects));\n const paddingObject = getPaddingObject(padding);\n function getBoundingClientRect() {\n // There are two rects and they are disjoined.\n if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) {\n // Find the first rect in which the point is fully inside.\n return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback;\n }\n\n // There are 2 or more connected rects.\n if (clientRects.length >= 2) {\n if (getSideAxis(placement) === 'y') {\n const firstRect = clientRects[0];\n const lastRect = clientRects[clientRects.length - 1];\n const isTop = getSide(placement) === 'top';\n const top = firstRect.top;\n const bottom = lastRect.bottom;\n const left = isTop ? firstRect.left : lastRect.left;\n const right = isTop ? firstRect.right : lastRect.right;\n const width = right - left;\n const height = bottom - top;\n return {\n top,\n bottom,\n left,\n right,\n width,\n height,\n x: left,\n y: top\n };\n }\n const isLeftSide = getSide(placement) === 'left';\n const maxRight = max(...clientRects.map(rect => rect.right));\n const minLeft = min(...clientRects.map(rect => rect.left));\n const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight);\n const top = measureRects[0].top;\n const bottom = measureRects[measureRects.length - 1].bottom;\n const left = minLeft;\n const right = maxRight;\n const width = right - left;\n const height = bottom - top;\n return {\n top,\n bottom,\n left,\n right,\n width,\n height,\n x: left,\n y: top\n };\n }\n return fallback;\n }\n const resetRects = await platform.getElementRects({\n reference: {\n getBoundingClientRect\n },\n floating: elements.floating,\n strategy\n });\n if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) {\n return {\n reset: {\n rects: resetRects\n }\n };\n }\n return {};\n }\n };\n};\n\n// For type backwards-compatibility, the `OffsetOptions` type was also\n// Derivable.\nasync function convertValueToCoords(state, options) {\n const {\n placement,\n platform,\n elements\n } = state;\n const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));\n const side = getSide(placement);\n const alignment = getAlignment(placement);\n const isVertical = getSideAxis(placement) === 'y';\n const mainAxisMulti = ['left', 'top'].includes(side) ? -1 : 1;\n const crossAxisMulti = rtl && isVertical ? -1 : 1;\n const rawValue = evaluate(options, state);\n\n // eslint-disable-next-line prefer-const\n let {\n mainAxis,\n crossAxis,\n alignmentAxis\n } = typeof rawValue === 'number' ? {\n mainAxis: rawValue,\n crossAxis: 0,\n alignmentAxis: null\n } : {\n mainAxis: 0,\n crossAxis: 0,\n alignmentAxis: null,\n ...rawValue\n };\n if (alignment && typeof alignmentAxis === 'number') {\n crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis;\n }\n return isVertical ? {\n x: crossAxis * crossAxisMulti,\n y: mainAxis * mainAxisMulti\n } : {\n x: mainAxis * mainAxisMulti,\n y: crossAxis * crossAxisMulti\n };\n}\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = function (options) {\n if (options === void 0) {\n options = 0;\n }\n return {\n name: 'offset',\n options,\n async fn(state) {\n var _middlewareData$offse, _middlewareData$arrow;\n const {\n x,\n y,\n placement,\n middlewareData\n } = state;\n const diffCoords = await convertValueToCoords(state, options);\n\n // If the placement is the same and the arrow caused an alignment offset\n // then we don't need to change the positioning coordinates.\n if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {\n return {};\n }\n return {\n x: x + diffCoords.x,\n y: y + diffCoords.y,\n data: {\n ...diffCoords,\n placement\n }\n };\n }\n };\n};\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'shift',\n options,\n async fn(state) {\n const {\n x,\n y,\n placement\n } = state;\n const {\n mainAxis: checkMainAxis = true,\n crossAxis: checkCrossAxis = false,\n limiter = {\n fn: _ref => {\n let {\n x,\n y\n } = _ref;\n return {\n x,\n y\n };\n }\n },\n ...detectOverflowOptions\n } = evaluate(options, state);\n const coords = {\n x,\n y\n };\n const overflow = await detectOverflow(state, detectOverflowOptions);\n const crossAxis = getSideAxis(getSide(placement));\n const mainAxis = getOppositeAxis(crossAxis);\n let mainAxisCoord = coords[mainAxis];\n let crossAxisCoord = coords[crossAxis];\n if (checkMainAxis) {\n const minSide = mainAxis === 'y' ? 'top' : 'left';\n const maxSide = mainAxis === 'y' ? 'bottom' : 'right';\n const min = mainAxisCoord + overflow[minSide];\n const max = mainAxisCoord - overflow[maxSide];\n mainAxisCoord = clamp(min, mainAxisCoord, max);\n }\n if (checkCrossAxis) {\n const minSide = crossAxis === 'y' ? 'top' : 'left';\n const maxSide = crossAxis === 'y' ? 'bottom' : 'right';\n const min = crossAxisCoord + overflow[minSide];\n const max = crossAxisCoord - overflow[maxSide];\n crossAxisCoord = clamp(min, crossAxisCoord, max);\n }\n const limitedCoords = limiter.fn({\n ...state,\n [mainAxis]: mainAxisCoord,\n [crossAxis]: crossAxisCoord\n });\n return {\n ...limitedCoords,\n data: {\n x: limitedCoords.x - x,\n y: limitedCoords.y - y\n }\n };\n }\n };\n};\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n options,\n fn(state) {\n const {\n x,\n y,\n placement,\n rects,\n middlewareData\n } = state;\n const {\n offset = 0,\n mainAxis: checkMainAxis = true,\n crossAxis: checkCrossAxis = true\n } = evaluate(options, state);\n const coords = {\n x,\n y\n };\n const crossAxis = getSideAxis(placement);\n const mainAxis = getOppositeAxis(crossAxis);\n let mainAxisCoord = coords[mainAxis];\n let crossAxisCoord = coords[crossAxis];\n const rawOffset = evaluate(offset, state);\n const computedOffset = typeof rawOffset === 'number' ? {\n mainAxis: rawOffset,\n crossAxis: 0\n } : {\n mainAxis: 0,\n crossAxis: 0,\n ...rawOffset\n };\n if (checkMainAxis) {\n const len = mainAxis === 'y' ? 'height' : 'width';\n const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis;\n const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis;\n if (mainAxisCoord < limitMin) {\n mainAxisCoord = limitMin;\n } else if (mainAxisCoord > limitMax) {\n mainAxisCoord = limitMax;\n }\n }\n if (checkCrossAxis) {\n var _middlewareData$offse, _middlewareData$offse2;\n const len = mainAxis === 'y' ? 'width' : 'height';\n const isOriginSide = ['top', 'left'].includes(getSide(placement));\n const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis);\n const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0);\n if (crossAxisCoord < limitMin) {\n crossAxisCoord = limitMin;\n } else if (crossAxisCoord > limitMax) {\n crossAxisCoord = limitMax;\n }\n }\n return {\n [mainAxis]: mainAxisCoord,\n [crossAxis]: crossAxisCoord\n };\n }\n };\n};\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'size',\n options,\n async fn(state) {\n const {\n placement,\n rects,\n platform,\n elements\n } = state;\n const {\n apply = () => {},\n ...detectOverflowOptions\n } = evaluate(options, state);\n const overflow = await detectOverflow(state, detectOverflowOptions);\n const side = getSide(placement);\n const alignment = getAlignment(placement);\n const isYAxis = getSideAxis(placement) === 'y';\n const {\n width,\n height\n } = rects.floating;\n let heightSide;\n let widthSide;\n if (side === 'top' || side === 'bottom') {\n heightSide = side;\n widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right';\n } else {\n widthSide = side;\n heightSide = alignment === 'end' ? 'top' : 'bottom';\n }\n const overflowAvailableHeight = height - overflow[heightSide];\n const overflowAvailableWidth = width - overflow[widthSide];\n const noShift = !state.middlewareData.shift;\n let availableHeight = overflowAvailableHeight;\n let availableWidth = overflowAvailableWidth;\n if (isYAxis) {\n const maximumClippingWidth = width - overflow.left - overflow.right;\n availableWidth = alignment || noShift ? min(overflowAvailableWidth, maximumClippingWidth) : maximumClippingWidth;\n } else {\n const maximumClippingHeight = height - overflow.top - overflow.bottom;\n availableHeight = alignment || noShift ? min(overflowAvailableHeight, maximumClippingHeight) : maximumClippingHeight;\n }\n if (noShift && !alignment) {\n const xMin = max(overflow.left, 0);\n const xMax = max(overflow.right, 0);\n const yMin = max(overflow.top, 0);\n const yMax = max(overflow.bottom, 0);\n if (isYAxis) {\n availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right));\n } else {\n availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom));\n }\n }\n await apply({\n ...state,\n availableWidth,\n availableHeight\n });\n const nextDimensions = await platform.getDimensions(elements.floating);\n if (width !== nextDimensions.width || height !== nextDimensions.height) {\n return {\n reset: {\n rects: true\n }\n };\n }\n return {};\n }\n };\n};\n\nexport { arrow, autoPlacement, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, shift, size };\n","import { rectToClientRect, computePosition as computePosition$1 } from '@floating-ui/core';\nexport { arrow, autoPlacement, detectOverflow, flip, hide, inline, limitShift, offset, shift, size } from '@floating-ui/core';\nimport { round, createCoords, max, min, floor } from '@floating-ui/utils';\nimport { getComputedStyle, isHTMLElement, isElement, getWindow, isWebKit, getDocumentElement, getNodeName, isOverflowElement, getNodeScroll, getOverflowAncestors, getParentNode, isLastTraversableNode, isContainingBlock, isTableElement, getContainingBlock } from '@floating-ui/utils/dom';\nexport { getOverflowAncestors } from '@floating-ui/utils/dom';\n\nfunction getCssDimensions(element) {\n const css = getComputedStyle(element);\n // In testing environments, the `width` and `height` properties are empty\n // strings for SVG elements, returning NaN. Fallback to `0` in this case.\n let width = parseFloat(css.width) || 0;\n let height = parseFloat(css.height) || 0;\n const hasOffset = isHTMLElement(element);\n const offsetWidth = hasOffset ? element.offsetWidth : width;\n const offsetHeight = hasOffset ? element.offsetHeight : height;\n const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;\n if (shouldFallback) {\n width = offsetWidth;\n height = offsetHeight;\n }\n return {\n width,\n height,\n $: shouldFallback\n };\n}\n\nfunction unwrapElement(element) {\n return !isElement(element) ? element.contextElement : element;\n}\n\nfunction getScale(element) {\n const domElement = unwrapElement(element);\n if (!isHTMLElement(domElement)) {\n return createCoords(1);\n }\n const rect = domElement.getBoundingClientRect();\n const {\n width,\n height,\n $\n } = getCssDimensions(domElement);\n let x = ($ ? round(rect.width) : rect.width) / width;\n let y = ($ ? round(rect.height) : rect.height) / height;\n\n // 0, NaN, or Infinity should always fallback to 1.\n\n if (!x || !Number.isFinite(x)) {\n x = 1;\n }\n if (!y || !Number.isFinite(y)) {\n y = 1;\n }\n return {\n x,\n y\n };\n}\n\nconst noOffsets = /*#__PURE__*/createCoords(0);\nfunction getVisualOffsets(element) {\n const win = getWindow(element);\n if (!isWebKit() || !win.visualViewport) {\n return noOffsets;\n }\n return {\n x: win.visualViewport.offsetLeft,\n y: win.visualViewport.offsetTop\n };\n}\nfunction shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {\n if (isFixed === void 0) {\n isFixed = false;\n }\n if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {\n return false;\n }\n return isFixed;\n}\n\nfunction getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {\n if (includeScale === void 0) {\n includeScale = false;\n }\n if (isFixedStrategy === void 0) {\n isFixedStrategy = false;\n }\n const clientRect = element.getBoundingClientRect();\n const domElement = unwrapElement(element);\n let scale = createCoords(1);\n if (includeScale) {\n if (offsetParent) {\n if (isElement(offsetParent)) {\n scale = getScale(offsetParent);\n }\n } else {\n scale = getScale(element);\n }\n }\n const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);\n let x = (clientRect.left + visualOffsets.x) / scale.x;\n let y = (clientRect.top + visualOffsets.y) / scale.y;\n let width = clientRect.width / scale.x;\n let height = clientRect.height / scale.y;\n if (domElement) {\n const win = getWindow(domElement);\n const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;\n let currentIFrame = win.frameElement;\n while (currentIFrame && offsetParent && offsetWin !== win) {\n const iframeScale = getScale(currentIFrame);\n const iframeRect = currentIFrame.getBoundingClientRect();\n const css = getComputedStyle(currentIFrame);\n const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;\n const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;\n x *= iframeScale.x;\n y *= iframeScale.y;\n width *= iframeScale.x;\n height *= iframeScale.y;\n x += left;\n y += top;\n currentIFrame = getWindow(currentIFrame).frameElement;\n }\n }\n return rectToClientRect({\n width,\n height,\n x,\n y\n });\n}\n\nfunction convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {\n let {\n rect,\n offsetParent,\n strategy\n } = _ref;\n const isOffsetParentAnElement = isHTMLElement(offsetParent);\n const documentElement = getDocumentElement(offsetParent);\n if (offsetParent === documentElement) {\n return rect;\n }\n let scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n let scale = createCoords(1);\n const offsets = createCoords(0);\n if (isOffsetParentAnElement || !isOffsetParentAnElement && strategy !== 'fixed') {\n if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n if (isHTMLElement(offsetParent)) {\n const offsetRect = getBoundingClientRect(offsetParent);\n scale = getScale(offsetParent);\n offsets.x = offsetRect.x + offsetParent.clientLeft;\n offsets.y = offsetRect.y + offsetParent.clientTop;\n }\n }\n return {\n width: rect.width * scale.x,\n height: rect.height * scale.y,\n x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x,\n y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y\n };\n}\n\nfunction getClientRects(element) {\n return Array.from(element.getClientRects());\n}\n\nfunction getWindowScrollBarX(element) {\n // If has a CSS width greater than the viewport, then this will be\n // incorrect for RTL.\n return getBoundingClientRect(getDocumentElement(element)).left + getNodeScroll(element).scrollLeft;\n}\n\n// Gets the entire size of the scrollable document area, even extending outside\n// of the `` and `` rect bounds if horizontally scrollable.\nfunction getDocumentRect(element) {\n const html = getDocumentElement(element);\n const scroll = getNodeScroll(element);\n const body = element.ownerDocument.body;\n const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);\n const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);\n let x = -scroll.scrollLeft + getWindowScrollBarX(element);\n const y = -scroll.scrollTop;\n if (getComputedStyle(body).direction === 'rtl') {\n x += max(html.clientWidth, body.clientWidth) - width;\n }\n return {\n width,\n height,\n x,\n y\n };\n}\n\nfunction getViewportRect(element, strategy) {\n const win = getWindow(element);\n const html = getDocumentElement(element);\n const visualViewport = win.visualViewport;\n let width = html.clientWidth;\n let height = html.clientHeight;\n let x = 0;\n let y = 0;\n if (visualViewport) {\n width = visualViewport.width;\n height = visualViewport.height;\n const visualViewportBased = isWebKit();\n if (!visualViewportBased || visualViewportBased && strategy === 'fixed') {\n x = visualViewport.offsetLeft;\n y = visualViewport.offsetTop;\n }\n }\n return {\n width,\n height,\n x,\n y\n };\n}\n\n// Returns the inner client rect, subtracting scrollbars if present.\nfunction getInnerBoundingClientRect(element, strategy) {\n const clientRect = getBoundingClientRect(element, true, strategy === 'fixed');\n const top = clientRect.top + element.clientTop;\n const left = clientRect.left + element.clientLeft;\n const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);\n const width = element.clientWidth * scale.x;\n const height = element.clientHeight * scale.y;\n const x = left * scale.x;\n const y = top * scale.y;\n return {\n width,\n height,\n x,\n y\n };\n}\nfunction getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {\n let rect;\n if (clippingAncestor === 'viewport') {\n rect = getViewportRect(element, strategy);\n } else if (clippingAncestor === 'document') {\n rect = getDocumentRect(getDocumentElement(element));\n } else if (isElement(clippingAncestor)) {\n rect = getInnerBoundingClientRect(clippingAncestor, strategy);\n } else {\n const visualOffsets = getVisualOffsets(element);\n rect = {\n ...clippingAncestor,\n x: clippingAncestor.x - visualOffsets.x,\n y: clippingAncestor.y - visualOffsets.y\n };\n }\n return rectToClientRect(rect);\n}\nfunction hasFixedPositionAncestor(element, stopNode) {\n const parentNode = getParentNode(element);\n if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {\n return false;\n }\n return getComputedStyle(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode);\n}\n\n// A \"clipping ancestor\" is an `overflow` element with the characteristic of\n// clipping (or hiding) child elements. This returns all clipping ancestors\n// of the given element up the tree.\nfunction getClippingElementAncestors(element, cache) {\n const cachedResult = cache.get(element);\n if (cachedResult) {\n return cachedResult;\n }\n let result = getOverflowAncestors(element, [], false).filter(el => isElement(el) && getNodeName(el) !== 'body');\n let currentContainingBlockComputedStyle = null;\n const elementIsFixed = getComputedStyle(element).position === 'fixed';\n let currentNode = elementIsFixed ? getParentNode(element) : element;\n\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {\n const computedStyle = getComputedStyle(currentNode);\n const currentNodeIsContaining = isContainingBlock(currentNode);\n if (!currentNodeIsContaining && computedStyle.position === 'fixed') {\n currentContainingBlockComputedStyle = null;\n }\n const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && ['absolute', 'fixed'].includes(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);\n if (shouldDropCurrentNode) {\n // Drop non-containing blocks.\n result = result.filter(ancestor => ancestor !== currentNode);\n } else {\n // Record last containing block for next iteration.\n currentContainingBlockComputedStyle = computedStyle;\n }\n currentNode = getParentNode(currentNode);\n }\n cache.set(element, result);\n return result;\n}\n\n// Gets the maximum area that the element is visible in due to any number of\n// clipping ancestors.\nfunction getClippingRect(_ref) {\n let {\n element,\n boundary,\n rootBoundary,\n strategy\n } = _ref;\n const elementClippingAncestors = boundary === 'clippingAncestors' ? getClippingElementAncestors(element, this._c) : [].concat(boundary);\n const clippingAncestors = [...elementClippingAncestors, rootBoundary];\n const firstClippingAncestor = clippingAncestors[0];\n const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {\n const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy);\n accRect.top = max(rect.top, accRect.top);\n accRect.right = min(rect.right, accRect.right);\n accRect.bottom = min(rect.bottom, accRect.bottom);\n accRect.left = max(rect.left, accRect.left);\n return accRect;\n }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy));\n return {\n width: clippingRect.right - clippingRect.left,\n height: clippingRect.bottom - clippingRect.top,\n x: clippingRect.left,\n y: clippingRect.top\n };\n}\n\nfunction getDimensions(element) {\n return getCssDimensions(element);\n}\n\nfunction getRectRelativeToOffsetParent(element, offsetParent, strategy) {\n const isOffsetParentAnElement = isHTMLElement(offsetParent);\n const documentElement = getDocumentElement(offsetParent);\n const isFixed = strategy === 'fixed';\n const rect = getBoundingClientRect(element, true, isFixed, offsetParent);\n let scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n const offsets = createCoords(0);\n if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n if (isOffsetParentAnElement) {\n const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);\n offsets.x = offsetRect.x + offsetParent.clientLeft;\n offsets.y = offsetRect.y + offsetParent.clientTop;\n } else if (documentElement) {\n offsets.x = getWindowScrollBarX(documentElement);\n }\n }\n return {\n x: rect.left + scroll.scrollLeft - offsets.x,\n y: rect.top + scroll.scrollTop - offsets.y,\n width: rect.width,\n height: rect.height\n };\n}\n\nfunction getTrueOffsetParent(element, polyfill) {\n if (!isHTMLElement(element) || getComputedStyle(element).position === 'fixed') {\n return null;\n }\n if (polyfill) {\n return polyfill(element);\n }\n return element.offsetParent;\n}\n\n// Gets the closest ancestor positioned element. Handles some edge cases,\n// such as table ancestors and cross browser bugs.\nfunction getOffsetParent(element, polyfill) {\n const window = getWindow(element);\n if (!isHTMLElement(element)) {\n return window;\n }\n let offsetParent = getTrueOffsetParent(element, polyfill);\n while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') {\n offsetParent = getTrueOffsetParent(offsetParent, polyfill);\n }\n if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static' && !isContainingBlock(offsetParent))) {\n return window;\n }\n return offsetParent || getContainingBlock(element) || window;\n}\n\nconst getElementRects = async function (_ref) {\n let {\n reference,\n floating,\n strategy\n } = _ref;\n const getOffsetParentFn = this.getOffsetParent || getOffsetParent;\n const getDimensionsFn = this.getDimensions;\n return {\n reference: getRectRelativeToOffsetParent(reference, await getOffsetParentFn(floating), strategy),\n floating: {\n x: 0,\n y: 0,\n ...(await getDimensionsFn(floating))\n }\n };\n};\n\nfunction isRTL(element) {\n return getComputedStyle(element).direction === 'rtl';\n}\n\nconst platform = {\n convertOffsetParentRelativeRectToViewportRelativeRect,\n getDocumentElement,\n getClippingRect,\n getOffsetParent,\n getElementRects,\n getClientRects,\n getDimensions,\n getScale,\n isElement,\n isRTL\n};\n\n// https://samthor.au/2021/observing-dom/\nfunction observeMove(element, onMove) {\n let io = null;\n let timeoutId;\n const root = getDocumentElement(element);\n function cleanup() {\n clearTimeout(timeoutId);\n io && io.disconnect();\n io = null;\n }\n function refresh(skip, threshold) {\n if (skip === void 0) {\n skip = false;\n }\n if (threshold === void 0) {\n threshold = 1;\n }\n cleanup();\n const {\n left,\n top,\n width,\n height\n } = element.getBoundingClientRect();\n if (!skip) {\n onMove();\n }\n if (!width || !height) {\n return;\n }\n const insetTop = floor(top);\n const insetRight = floor(root.clientWidth - (left + width));\n const insetBottom = floor(root.clientHeight - (top + height));\n const insetLeft = floor(left);\n const rootMargin = -insetTop + \"px \" + -insetRight + \"px \" + -insetBottom + \"px \" + -insetLeft + \"px\";\n const options = {\n rootMargin,\n threshold: max(0, min(1, threshold)) || 1\n };\n let isFirstUpdate = true;\n function handleObserve(entries) {\n const ratio = entries[0].intersectionRatio;\n if (ratio !== threshold) {\n if (!isFirstUpdate) {\n return refresh();\n }\n if (!ratio) {\n timeoutId = setTimeout(() => {\n refresh(false, 1e-7);\n }, 100);\n } else {\n refresh(false, ratio);\n }\n }\n isFirstUpdate = false;\n }\n\n // Older browsers don't support a `document` as the root and will throw an\n // error.\n try {\n io = new IntersectionObserver(handleObserve, {\n ...options,\n // Handle