{"version":3,"file":"static/js/main.5d67d3c6.js","sources":["../node_modules/@daily-co/daily-js/dist/daily-esm.js","../node_modules/@segment/analytics-core/src/callback/index.ts","../node_modules/@segment/analytics-core/src/logger/index.ts","../node_modules/@segment/analytics-core/src/context/index.ts","../node_modules/@segment/analytics-core/src/priority-queue/index.ts","../node_modules/@segment/analytics-core/src/priority-queue/backoff.ts","../node_modules/@segment/analytics-core/src/queue/delivery.ts","../node_modules/@segment/analytics-core/src/stats/index.ts","../node_modules/@segment/analytics-core/src/validation/helpers.ts","../node_modules/@segment/analytics-generic-utils/src/create-deferred/create-deferred.ts","../node_modules/@segment/analytics-generic-utils/src/emitter/emitter.ts","../node_modules/@segment/analytics-next/src/core/connection/index.ts","../node_modules/@segment/analytics-next/src/core/constants/index.ts","../node_modules/@segment/analytics-next/src/core/context/index.ts","../node_modules/@segment/analytics-next/src/core/environment/index.ts","../node_modules/@segment/analytics-next/src/core/query-string/gracefulDecodeURIComponent.ts","../node_modules/@segment/analytics-next/src/core/stats/remote-metrics.ts","../node_modules/@segment/analytics-next/src/core/stats/index.ts","../node_modules/@segment/analytics-next/src/core/stats/metric-helpers.ts","../node_modules/@segment/analytics-next/src/generated/version.ts","../node_modules/unfetch/src/index.mjs","../node_modules/@segment/analytics-next/src/lib/fetch.ts","../node_modules/@segment/analytics-next/src/lib/get-global.ts","../node_modules/@segment/analytics-next/src/lib/global-analytics-helper.ts","../node_modules/@segment/analytics-next/src/lib/load-script.ts","../node_modules/@segment/analytics-next/src/lib/merged-options.ts","../node_modules/@segment/analytics-next/src/lib/p-while.ts","../node_modules/@segment/analytics-next/src/lib/parse-cdn.ts","../node_modules/@segment/analytics-next/src/lib/priority-queue/persisted.ts","../node_modules/@segment/analytics-next/src/lib/to-facade.ts","../node_modules/@segment/analytics-next/src/lib/version-type.ts","../node_modules/@segment/analytics-next/src/plugins/middleware/index.ts","../node_modules/@segment/facade/lib/address.js","../node_modules/@segment/facade/lib/alias.js","../node_modules/@segment/facade/lib/clone.js","../node_modules/@segment/facade/lib/delete.js","../node_modules/@segment/facade/lib/facade.js","../node_modules/@segment/facade/lib/group.js","../node_modules/@segment/facade/lib/identify.js","../node_modules/@segment/facade/lib/index.js","../node_modules/@segment/facade/lib/is-email.js","../node_modules/@segment/facade/lib/is-enabled.js","../node_modules/@segment/facade/lib/page.js","../node_modules/@segment/facade/lib/screen.js","../node_modules/@segment/facade/lib/track.js","../node_modules/@segment/isodate-traverse/lib/index.js","../node_modules/@segment/isodate/lib/index.js","../node_modules/@vapi-ai/web/dist/api.js","../node_modules/@vapi-ai/web/dist/client.js","../node_modules/@vapi-ai/web/dist/vapi.js","../node_modules/decimal.js-light/decimal.js","../node_modules/eventemitter3/index.js","../node_modules/events/events.js","../node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js","../node_modules/hoist-non-react-statics/node_modules/react-is/cjs/react-is.production.min.js","../node_modules/hoist-non-react-statics/node_modules/react-is/index.js","../node_modules/inherits/inherits_browser.js","../node_modules/lodash/_DataView.js","../node_modules/lodash/_Hash.js","../node_modules/lodash/_ListCache.js","../node_modules/lodash/_Map.js","../node_modules/lodash/_MapCache.js","../node_modules/lodash/_Promise.js","../node_modules/lodash/_Set.js","../node_modules/lodash/_SetCache.js","../node_modules/lodash/_Stack.js","../node_modules/lodash/_Symbol.js","../node_modules/lodash/_Uint8Array.js","../node_modules/lodash/_WeakMap.js","../node_modules/lodash/_apply.js","../node_modules/lodash/_arrayEvery.js","../node_modules/lodash/_arrayFilter.js","../node_modules/lodash/_arrayIncludes.js","../node_modules/lodash/_arrayIncludesWith.js","../node_modules/lodash/_arrayLikeKeys.js","../node_modules/lodash/_arrayMap.js","../node_modules/lodash/_arrayPush.js","../node_modules/lodash/_arraySome.js","../node_modules/lodash/_asciiToArray.js","../node_modules/lodash/_assocIndexOf.js","../node_modules/lodash/_baseAssignValue.js","../node_modules/lodash/_baseEach.js","../node_modules/lodash/_baseEvery.js","../node_modules/lodash/_baseExtremum.js","../node_modules/lodash/_baseFindIndex.js","../node_modules/lodash/_baseFlatten.js","../node_modules/lodash/_baseFor.js","../node_modules/lodash/_baseForOwn.js","../node_modules/lodash/_baseGet.js","../node_modules/lodash/_baseGetAllKeys.js","../node_modules/lodash/_baseGetTag.js","../node_modules/lodash/_baseGt.js","../node_modules/lodash/_baseHasIn.js","../node_modules/lodash/_baseIndexOf.js","../node_modules/lodash/_baseIsArguments.js","../node_modules/lodash/_baseIsEqual.js","../node_modules/lodash/_baseIsEqualDeep.js","../node_modules/lodash/_baseIsMatch.js","../node_modules/lodash/_baseIsNaN.js","../node_modules/lodash/_baseIsNative.js","../node_modules/lodash/_baseIsTypedArray.js","../node_modules/lodash/_baseIteratee.js","../node_modules/lodash/_baseKeys.js","../node_modules/lodash/_baseLt.js","../node_modules/lodash/_baseMap.js","../node_modules/lodash/_baseMatches.js","../node_modules/lodash/_baseMatchesProperty.js","../node_modules/lodash/_baseOrderBy.js","../node_modules/lodash/_baseProperty.js","../node_modules/lodash/_basePropertyDeep.js","../node_modules/lodash/_baseRange.js","../node_modules/lodash/_baseRest.js","../node_modules/lodash/_baseSetToString.js","../node_modules/lodash/_baseSlice.js","../node_modules/lodash/_baseSome.js","../node_modules/lodash/_baseSortBy.js","../node_modules/lodash/_baseTimes.js","../node_modules/lodash/_baseToString.js","../node_modules/lodash/_baseTrim.js","../node_modules/lodash/_baseUnary.js","../node_modules/lodash/_baseUniq.js","../node_modules/lodash/_cacheHas.js","../node_modules/lodash/_castPath.js","../node_modules/lodash/_castSlice.js","../node_modules/lodash/_compareAscending.js","../node_modules/lodash/_compareMultiple.js","../node_modules/lodash/_coreJsData.js","../node_modules/lodash/_createBaseEach.js","../node_modules/lodash/_createBaseFor.js","../node_modules/lodash/_createCaseFirst.js","../node_modules/lodash/_createFind.js","../node_modules/lodash/_createRange.js","../node_modules/lodash/_createSet.js","../node_modules/lodash/_defineProperty.js","../node_modules/lodash/_equalArrays.js","../node_modules/lodash/_equalByTag.js","../node_modules/lodash/_equalObjects.js","../node_modules/lodash/_freeGlobal.js","../node_modules/lodash/_getAllKeys.js","../node_modules/lodash/_getMapData.js","../node_modules/lodash/_getMatchData.js","../node_modules/lodash/_getNative.js","../node_modules/lodash/_getPrototype.js","../node_modules/lodash/_getRawTag.js","../node_modules/lodash/_getSymbols.js","../node_modules/lodash/_getTag.js","../node_modules/lodash/_getValue.js","../node_modules/lodash/_hasPath.js","../node_modules/lodash/_hasUnicode.js","../node_modules/lodash/_hashClear.js","../node_modules/lodash/_hashDelete.js","../node_modules/lodash/_hashGet.js","../node_modules/lodash/_hashHas.js","../node_modules/lodash/_hashSet.js","../node_modules/lodash/_isFlattenable.js","../node_modules/lodash/_isIndex.js","../node_modules/lodash/_isIterateeCall.js","../node_modules/lodash/_isKey.js","../node_modules/lodash/_isKeyable.js","../node_modules/lodash/_isMasked.js","../node_modules/lodash/_isPrototype.js","../node_modules/lodash/_isStrictComparable.js","../node_modules/lodash/_listCacheClear.js","../node_modules/lodash/_listCacheDelete.js","../node_modules/lodash/_listCacheGet.js","../node_modules/lodash/_listCacheHas.js","../node_modules/lodash/_listCacheSet.js","../node_modules/lodash/_mapCacheClear.js","../node_modules/lodash/_mapCacheDelete.js","../node_modules/lodash/_mapCacheGet.js","../node_modules/lodash/_mapCacheHas.js","../node_modules/lodash/_mapCacheSet.js","../node_modules/lodash/_mapToArray.js","../node_modules/lodash/_matchesStrictComparable.js","../node_modules/lodash/_memoizeCapped.js","../node_modules/lodash/_nativeCreate.js","../node_modules/lodash/_nativeKeys.js","../node_modules/lodash/_nodeUtil.js","../node_modules/lodash/_objectToString.js","../node_modules/lodash/_overArg.js","../node_modules/lodash/_overRest.js","../node_modules/lodash/_root.js","../node_modules/lodash/_setCacheAdd.js","../node_modules/lodash/_setCacheHas.js","../node_modules/lodash/_setToArray.js","../node_modules/lodash/_setToString.js","../node_modules/lodash/_shortOut.js","../node_modules/lodash/_stackClear.js","../node_modules/lodash/_stackDelete.js","../node_modules/lodash/_stackGet.js","../node_modules/lodash/_stackHas.js","../node_modules/lodash/_stackSet.js","../node_modules/lodash/_strictIndexOf.js","../node_modules/lodash/_stringToArray.js","../node_modules/lodash/_stringToPath.js","../node_modules/lodash/_toKey.js","../node_modules/lodash/_toSource.js","../node_modules/lodash/_trimmedEndIndex.js","../node_modules/lodash/_unicodeToArray.js","../node_modules/lodash/constant.js","../node_modules/lodash/debounce.js","../node_modules/lodash/eq.js","../node_modules/lodash/every.js","../node_modules/lodash/find.js","../node_modules/lodash/findIndex.js","../node_modules/lodash/flatMap.js","../node_modules/lodash/get.js","../node_modules/lodash/hasIn.js","../node_modules/lodash/identity.js","../node_modules/lodash/isArguments.js","../node_modules/lodash/isArray.js","../node_modules/lodash/isArrayLike.js","../node_modules/lodash/isBoolean.js","../node_modules/lodash/isBuffer.js","../node_modules/lodash/isEqual.js","../node_modules/lodash/isFunction.js","../node_modules/lodash/isLength.js","../node_modules/lodash/isNaN.js","../node_modules/lodash/isNil.js","../node_modules/lodash/isNumber.js","../node_modules/lodash/isObject.js","../node_modules/lodash/isObjectLike.js","../node_modules/lodash/isPlainObject.js","../node_modules/lodash/isString.js","../node_modules/lodash/isSymbol.js","../node_modules/lodash/isTypedArray.js","../node_modules/lodash/keys.js","../node_modules/lodash/last.js","../node_modules/lodash/map.js","../node_modules/lodash/mapValues.js","../node_modules/lodash/max.js","../node_modules/lodash/memoize.js","../node_modules/lodash/min.js","../node_modules/lodash/noop.js","../node_modules/lodash/now.js","../node_modules/lodash/property.js","../node_modules/lodash/range.js","../node_modules/lodash/some.js","../node_modules/lodash/sortBy.js","../node_modules/lodash/stubArray.js","../node_modules/lodash/stubFalse.js","../node_modules/lodash/throttle.js","../node_modules/lodash/toFinite.js","../node_modules/lodash/toInteger.js","../node_modules/lodash/toNumber.js","../node_modules/lodash/toString.js","../node_modules/lodash/uniqBy.js","../node_modules/lodash/upperFirst.js","../node_modules/new-date/lib/index.js","../node_modules/new-date/lib/milliseconds.js","../node_modules/new-date/lib/seconds.js","../node_modules/obj-case/index.js","../node_modules/prop-types/factoryWithThrowingShims.js","../node_modules/prop-types/index.js","../node_modules/prop-types/lib/ReactPropTypesSecret.js","../node_modules/quick-format-unescaped/index.js","../node_modules/react-dom/cjs/react-dom.production.min.js","../node_modules/react-dom/client.js","../node_modules/react-dom/index.js","../node_modules/react-is/cjs/react-is.production.min.js","../node_modules/react-is/index.js","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/react/cjs/react.production.min.js","../node_modules/react/index.js","../node_modules/react/jsx-runtime.js","../node_modules/scheduler/cjs/scheduler.production.min.js","../node_modules/scheduler/index.js","../node_modules/@babel/runtime/helpers/defineProperty.js","../node_modules/@babel/runtime/helpers/toPrimitive.js","../node_modules/@babel/runtime/helpers/toPropertyKey.js","../node_modules/@babel/runtime/helpers/typeof.js","../node_modules/pino/browser.js","../node_modules/@lukeed/uuid/dist/index.mjs","../node_modules/dset/dist/index.mjs","../node_modules/tslib/tslib.es6.mjs","../webpack/bootstrap","../webpack/runtime/compat get default export","../webpack/runtime/create fake namespace object","../webpack/runtime/define property getters","../webpack/runtime/ensure chunk","../webpack/runtime/get javascript chunk filename","../webpack/runtime/get mini-css chunk filename","../webpack/runtime/global","../webpack/runtime/hasOwnProperty shorthand","../webpack/runtime/load script","../webpack/runtime/make namespace object","../webpack/runtime/node module decorator","../webpack/runtime/publicPath","../webpack/runtime/jsonp chunk loading","../node_modules/@propelauth/react/node_modules/@propelauth/javascript/dist/esm/index.js","../node_modules/@propelauth/react/src/hooks/useActiveOrg.tsx","../node_modules/@propelauth/react/src/useClientRef.tsx","../node_modules/@propelauth/react/src/AuthContext.tsx","../node_modules/@propelauth/react/src/hooks/useAuthInfo.ts","../node_modules/@propelauth/react/src/hooks/useRedirectFunctions.tsx","../node_modules/@propelauth/react/node_modules/react-is/cjs/react-is.production.min.js","../node_modules/@propelauth/react/node_modules/react-is/cjs/react-is.development.js","../node_modules/@propelauth/react/node_modules/react-is/index.js","../node_modules/@propelauth/react/node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js","../node_modules/@propelauth/react/src/RequiredAuthProvider.tsx","../node_modules/@propelauth/react/src/withRequiredAuthInfo.tsx","../node_modules/@remix-run/router/history.ts","../node_modules/@remix-run/router/utils.ts","../node_modules/@remix-run/router/router.ts","../node_modules/react-router/lib/context.ts","../node_modules/react-router/lib/hooks.tsx","../node_modules/react-router/lib/components.tsx","../node_modules/react-router-dom/dom.ts","../node_modules/react-router-dom/index.tsx","../node_modules/clsx/dist/clsx.mjs","../node_modules/@babel/runtime/helpers/esm/extends.js","../node_modules/@emotion/memoize/dist/emotion-memoize.esm.js","../node_modules/@emotion/is-prop-valid/dist/emotion-is-prop-valid.esm.js","../node_modules/@emotion/cache/node_modules/@emotion/sheet/dist/emotion-sheet.browser.esm.js","../node_modules/stylis/src/Utility.js","../node_modules/stylis/src/Tokenizer.js","../node_modules/stylis/src/Enum.js","../node_modules/stylis/src/Serializer.js","../node_modules/stylis/src/Middleware.js","../node_modules/stylis/src/Parser.js","../node_modules/@emotion/cache/dist/emotion-cache.browser.esm.js","../node_modules/@emotion/serialize/node_modules/@emotion/unitless/dist/emotion-unitless.esm.js","../node_modules/@emotion/serialize/node_modules/@emotion/memoize/dist/emotion-memoize.esm.js","../node_modules/@emotion/serialize/dist/emotion-serialize.esm.js","../node_modules/@emotion/hash/dist/emotion-hash.esm.js","../node_modules/@emotion/use-insertion-effect-with-fallbacks/dist/emotion-use-insertion-effect-with-fallbacks.browser.esm.js","../node_modules/@emotion/react/dist/emotion-element-43c6fea0.browser.esm.js","../node_modules/@emotion/utils/dist/emotion-utils.browser.esm.js","../node_modules/@emotion/styled/base/dist/emotion-styled-base.browser.esm.js","../node_modules/@emotion/styled/dist/emotion-styled.browser.esm.js","../node_modules/@mui/styled-engine/index.js","../node_modules/@mui/utils/esm/formatMuiErrorMessage/formatMuiErrorMessage.js","../node_modules/@mui/utils/esm/capitalize/capitalize.js","../node_modules/@mui/utils/esm/deepmerge/deepmerge.js","../node_modules/@mui/system/esm/merge/merge.js","../node_modules/@mui/system/esm/breakpoints/breakpoints.js","../node_modules/@mui/system/esm/cssContainerQueries/cssContainerQueries.js","../node_modules/@mui/system/esm/style/style.js","../node_modules/@mui/system/esm/spacing/spacing.js","../node_modules/@mui/system/esm/memoize/memoize.js","../node_modules/@mui/system/esm/compose/compose.js","../node_modules/@mui/system/esm/borders/borders.js","../node_modules/@mui/system/esm/cssGrid/cssGrid.js","../node_modules/@mui/system/esm/palette/palette.js","../node_modules/@mui/system/esm/sizing/sizing.js","../node_modules/@mui/system/esm/styleFunctionSx/defaultSxConfig.js","../node_modules/@mui/system/esm/styleFunctionSx/styleFunctionSx.js","../node_modules/@mui/system/esm/styleFunctionSx/extendSxProp.js","../node_modules/@mui/system/esm/createBreakpoints/createBreakpoints.js","../node_modules/@mui/system/esm/createTheme/shape.js","../node_modules/@mui/system/esm/createTheme/createSpacing.js","../node_modules/@mui/system/esm/createTheme/applyStyles.js","../node_modules/@mui/system/esm/createTheme/createTheme.js","../node_modules/@mui/system/esm/useThemeWithoutDefault/useThemeWithoutDefault.js","../node_modules/@mui/system/esm/useTheme/useTheme.js","../node_modules/@mui/utils/esm/ClassNameGenerator/ClassNameGenerator.js","../node_modules/@mui/utils/esm/clamp/clamp.js","../node_modules/@mui/system/esm/colorManipulator/colorManipulator.js","../node_modules/@mui/material/colors/common.js","../node_modules/@mui/material/colors/grey.js","../node_modules/@mui/material/colors/purple.js","../node_modules/@mui/material/colors/red.js","../node_modules/@mui/material/colors/orange.js","../node_modules/@mui/material/colors/blue.js","../node_modules/@mui/material/colors/lightBlue.js","../node_modules/@mui/material/colors/green.js","../node_modules/@mui/material/styles/createPalette.js","../node_modules/@mui/system/esm/cssVars/createGetCssVar.js","../node_modules/@mui/system/esm/cssVars/prepareTypographyVars.js","../node_modules/@mui/system/esm/cssVars/cssVarsParser.js","../node_modules/@mui/system/esm/cssVars/prepareCssVars.js","../node_modules/@mui/material/styles/createMixins.js","../node_modules/@mui/material/styles/createTypography.js","../node_modules/@mui/material/styles/shadows.js","../node_modules/@mui/material/styles/createTransitions.js","../node_modules/@mui/material/styles/zIndex.js","../node_modules/@mui/material/styles/createThemeNoVars.js","../node_modules/@mui/material/styles/getOverlayAlpha.js","../node_modules/@mui/material/styles/createColorScheme.js","../node_modules/@mui/material/styles/shouldSkipGeneratingVar.js","../node_modules/@mui/material/styles/excludeVariablesFromRoot.js","../node_modules/@mui/material/styles/createGetSelector.js","../node_modules/@mui/material/styles/stringifyTheme.js","../node_modules/@mui/material/styles/createThemeWithVars.js","../node_modules/@mui/material/styles/createTheme.js","../node_modules/@mui/system/esm/cssVars/getColorSchemeSelector.js","../node_modules/@mui/material/styles/identifier.js","../node_modules/@mui/utils/esm/generateUtilityClass/generateUtilityClass.js","../node_modules/@mui/utils/esm/generateUtilityClasses/generateUtilityClasses.js","../node_modules/@mui/material/Box/boxClasses.js","../node_modules/@mui/material/Box/Box.js","../node_modules/@mui/system/esm/createBox/createBox.js","../node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js","../node_modules/@mui/utils/esm/composeClasses/composeClasses.js","../node_modules/@emotion/react/dist/emotion-react.browser.esm.js","../node_modules/@mui/system/esm/preprocessStyles.js","../node_modules/@mui/system/esm/createStyled/createStyled.js","../node_modules/@mui/material/styles/defaultTheme.js","../node_modules/@mui/material/styles/slotShouldForwardProp.js","../node_modules/@mui/material/styles/rootShouldForwardProp.js","../node_modules/@mui/material/styles/styled.js","../node_modules/@mui/system/esm/memoTheme.js","../node_modules/@mui/material/utils/memoTheme.js","../node_modules/@mui/utils/esm/resolveProps/resolveProps.js","../node_modules/@mui/system/esm/DefaultPropsProvider/DefaultPropsProvider.js","../node_modules/@mui/material/DefaultPropsProvider/DefaultPropsProvider.js","../node_modules/@mui/material/utils/capitalize.js","../node_modules/@mui/material/utils/createSimplePaletteValueFilter.js","../node_modules/@mui/material/CircularProgress/circularProgressClasses.js","../node_modules/@mui/material/CircularProgress/CircularProgress.js","../node_modules/@mui/utils/esm/setRef/setRef.js","../node_modules/@mui/utils/esm/useForkRef/useForkRef.js","../node_modules/@mui/utils/esm/isHostComponent/isHostComponent.js","../node_modules/@mui/utils/esm/appendOwnerState/appendOwnerState.js","../node_modules/@mui/utils/esm/extractEventHandlers/extractEventHandlers.js","../node_modules/@mui/utils/esm/omitEventHandlers/omitEventHandlers.js","../node_modules/@mui/utils/esm/mergeSlotProps/mergeSlotProps.js","../node_modules/@mui/utils/esm/resolveComponentProps/resolveComponentProps.js","../node_modules/@mui/utils/esm/useSlotProps/useSlotProps.js","../node_modules/@babel/runtime/helpers/esm/typeof.js","../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js","../node_modules/@babel/runtime/helpers/esm/toPrimitive.js","../node_modules/@babel/runtime/helpers/esm/defineProperty.js","../node_modules/@mui/utils/esm/useLazyRef/useLazyRef.js","../node_modules/@mui/utils/esm/useOnMount/useOnMount.js","../node_modules/@mui/utils/esm/useTimeout/useTimeout.js","../node_modules/@mui/utils/esm/useEnhancedEffect/useEnhancedEffect.js","../node_modules/@mui/utils/esm/useEventCallback/useEventCallback.js","../node_modules/@mui/material/Snackbar/useSnackbar.js","../node_modules/@mui/utils/esm/ownerDocument/ownerDocument.js","../node_modules/@mui/utils/esm/getReactElementRef/getReactElementRef.js","../node_modules/@mui/material/ClickAwayListener/ClickAwayListener.js","../node_modules/@mui/material/styles/useTheme.js","../node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js","../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","../node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","../node_modules/react-transition-group/esm/config.js","../node_modules/react-transition-group/esm/TransitionGroupContext.js","../node_modules/react-transition-group/esm/utils/reflow.js","../node_modules/react-transition-group/esm/Transition.js","../node_modules/@mui/material/transitions/utils.js","../node_modules/@mui/material/utils/useForkRef.js","../node_modules/@mui/material/Grow/Grow.js","../node_modules/@mui/material/Paper/paperClasses.js","../node_modules/@mui/material/Paper/Paper.js","../node_modules/@mui/material/SnackbarContent/snackbarContentClasses.js","../node_modules/@mui/material/SnackbarContent/SnackbarContent.js","../node_modules/@mui/material/Snackbar/snackbarClasses.js","../node_modules/@mui/material/Snackbar/Snackbar.js","../node_modules/@mui/material/utils/useSlot.js","../node_modules/@mui/material/Alert/alertClasses.js","../node_modules/@mui/utils/esm/isFocusVisible/isFocusVisible.js","../node_modules/@mui/material/utils/useEventCallback.js","../node_modules/@mui/material/useLazyRipple/useLazyRipple.js","../node_modules/react-transition-group/esm/utils/ChildMapping.js","../node_modules/react-transition-group/esm/TransitionGroup.js","../node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","../node_modules/@mui/material/ButtonBase/Ripple.js","../node_modules/@mui/material/ButtonBase/touchRippleClasses.js","../node_modules/@mui/material/ButtonBase/TouchRipple.js","../node_modules/@mui/material/ButtonBase/buttonBaseClasses.js","../node_modules/@mui/material/ButtonBase/ButtonBase.js","../node_modules/@mui/material/IconButton/iconButtonClasses.js","../node_modules/@mui/material/IconButton/IconButton.js","../node_modules/@mui/material/SvgIcon/svgIconClasses.js","../node_modules/@mui/material/SvgIcon/SvgIcon.js","../node_modules/@mui/material/utils/createSvgIcon.js","../node_modules/@mui/material/internal/svg-icons/SuccessOutlined.js","../node_modules/@mui/material/internal/svg-icons/ReportProblemOutlined.js","../node_modules/@mui/material/internal/svg-icons/ErrorOutline.js","../node_modules/@mui/material/internal/svg-icons/InfoOutlined.js","../node_modules/@mui/material/internal/svg-icons/Close.js","../node_modules/@mui/material/Alert/Alert.js","../node_modules/@mui/material/AppBar/appBarClasses.js","../node_modules/@mui/material/AppBar/AppBar.js","../node_modules/@mui/material/Toolbar/toolbarClasses.js","../node_modules/@mui/material/Toolbar/Toolbar.js","../node_modules/@mui/material/Button/buttonClasses.js","../node_modules/@mui/material/ButtonGroup/ButtonGroupContext.js","../node_modules/@mui/material/ButtonGroup/ButtonGroupButtonContext.js","../node_modules/@mui/material/Button/Button.js","../node_modules/@mui/styled-engine/GlobalStyles/GlobalStyles.js","../node_modules/@mui/system/esm/GlobalStyles/GlobalStyles.js","../node_modules/@mui/material/GlobalStyles/GlobalStyles.js","../node_modules/@mui/material/Typography/typographyClasses.js","../node_modules/@mui/material/Typography/Typography.js","../node_modules/@mui/material/zero-styled/index.js","../node_modules/@mui/material/internal/svg-icons/Person.js","../node_modules/@mui/material/Avatar/avatarClasses.js","../node_modules/@mui/material/Avatar/Avatar.js","../node_modules/@mui/system/esm/RtlProvider/index.js","../node_modules/@mui/material/utils/ownerDocument.js","../node_modules/@mui/material/List/ListContext.js","../node_modules/@mui/material/List/listClasses.js","../node_modules/@mui/material/List/List.js","../node_modules/@mui/utils/esm/getScrollbarSize/getScrollbarSize.js","../node_modules/@mui/material/utils/getScrollbarSize.js","../node_modules/@mui/material/utils/useEnhancedEffect.js","../node_modules/@mui/utils/esm/ownerWindow/ownerWindow.js","../node_modules/@mui/material/utils/ownerWindow.js","../node_modules/@mui/material/MenuList/MenuList.js","../node_modules/@mui/material/utils/isHostComponent.js","../node_modules/@mui/utils/esm/debounce/debounce.js","../node_modules/@mui/material/utils/debounce.js","../node_modules/@mui/material/Unstable_TrapFocus/FocusTrap.js","../node_modules/@mui/material/Portal/Portal.js","../node_modules/@mui/material/Fade/Fade.js","../node_modules/@mui/material/Backdrop/backdropClasses.js","../node_modules/@mui/material/Backdrop/Backdrop.js","../node_modules/@mui/utils/esm/createChainedFunction/createChainedFunction.js","../node_modules/@mui/material/Modal/ModalManager.js","../node_modules/@mui/material/Modal/useModal.js","../node_modules/@mui/material/Modal/modalClasses.js","../node_modules/@mui/material/Modal/Modal.js","../node_modules/@mui/material/Popover/popoverClasses.js","../node_modules/@mui/material/Popover/Popover.js","../node_modules/@mui/material/Menu/menuClasses.js","../node_modules/@mui/material/Menu/Menu.js","../node_modules/@mui/material/Divider/dividerClasses.js","../node_modules/@mui/material/ListItemIcon/listItemIconClasses.js","../node_modules/@mui/material/ListItemText/listItemTextClasses.js","../node_modules/@mui/material/MenuItem/menuItemClasses.js","../node_modules/@mui/material/MenuItem/MenuItem.js","../node_modules/@mui/icons-material/esm/Settings.js","../node_modules/@mui/icons-material/esm/Help.js","../node_modules/@mui/icons-material/esm/Logout.js","../node_modules/@mui/utils/esm/isMuiElement/isMuiElement.js","../node_modules/@mui/material/utils/isMuiElement.js","../node_modules/@mui/material/ListItem/listItemClasses.js","../node_modules/@mui/material/ListItemButton/listItemButtonClasses.js","../node_modules/@mui/material/ListItemSecondaryAction/listItemSecondaryActionClasses.js","../node_modules/@mui/material/ListItemSecondaryAction/ListItemSecondaryAction.js","../node_modules/@mui/material/ListItem/ListItem.js","../node_modules/@mui/utils/esm/useId/useId.js","../node_modules/@mui/material/Dialog/dialogClasses.js","../node_modules/@mui/material/Dialog/DialogContext.js","../node_modules/@mui/material/Dialog/Dialog.js","../node_modules/@mui/material/DialogTitle/dialogTitleClasses.js","../node_modules/@mui/material/DialogTitle/DialogTitle.js","../node_modules/@mui/material/DialogContent/dialogContentClasses.js","../node_modules/@mui/material/DialogContent/DialogContent.js","../node_modules/@mui/material/ListItemIcon/ListItemIcon.js","../node_modules/@mui/material/ListItemText/ListItemText.js","../node_modules/@mui/material/Divider/Divider.js","../node_modules/@mui/material/DialogActions/dialogActionsClasses.js","../node_modules/@mui/material/DialogActions/DialogActions.js","../node_modules/@mui/icons-material/esm/PlayArrow.js","../node_modules/@mui/icons-material/esm/History.js","../node_modules/@mui/icons-material/esm/Assessment.js","../node_modules/@mui/icons-material/esm/Email.js","../node_modules/@mui/icons-material/esm/Dashboard.js","components/Dashboard/HelpModal.js","../node_modules/@mui/icons-material/esm/CreditCard.js","../node_modules/@segment/analytics-next/src/lib/get-process-env.ts","../node_modules/@segment/analytics-next/src/core/arguments-resolver/index.ts","../node_modules/@segment/analytics-core/src/analytics/dispatch.ts","../node_modules/@segment/analytics-next/src/core/page/get-page-context.ts","../node_modules/@segment/analytics-next/src/core/page/add-page-context.ts","../node_modules/@segment/analytics-next/src/lib/pick.ts","../node_modules/@segment/analytics-core/src/validation/errors.ts","../node_modules/@segment/analytics-core/src/validation/assertions.ts","../node_modules/@segment/analytics-core/src/events/index.ts","../node_modules/@segment/analytics-core/src/utils/pick.ts","../node_modules/@segment/analytics-next/src/core/events/index.ts","../node_modules/@segment/analytics-next/src/core/plugin/index.ts","../node_modules/@segment/analytics-core/src/queue/event-queue.ts","../node_modules/@segment/analytics-core/src/task/task-group.ts","../node_modules/@segment/analytics-core/src/utils/is-thenable.ts","../node_modules/@segment/analytics-core/src/utils/group-by.ts","../node_modules/@segment/analytics-next/src/core/queue/event-queue.ts","../node_modules/@segment/analytics-next/src/lib/bind-all.ts","../node_modules/@segment/analytics-next/src/core/storage/types.ts","../node_modules/@segment/analytics-next/src/core/storage/universalStorage.ts","../node_modules/@segment/analytics-next/src/core/storage/memoryStorage.ts","../node_modules/@segment/analytics-next/src/core/storage/settings.ts","../node_modules/js-cookie/dist/js.cookie.mjs","../node_modules/@segment/analytics-next/src/core/user/tld.ts","../node_modules/@segment/analytics-next/src/core/storage/cookieStorage.ts","../node_modules/@segment/analytics-next/src/core/storage/localStorage.ts","../node_modules/@segment/analytics-next/src/core/storage/index.ts","../node_modules/@segment/analytics-next/src/core/user/index.ts","../node_modules/@segment/analytics-next/src/core/buffer/index.ts","../node_modules/@segment/analytics-next/src/lib/is-thenable.ts","../node_modules/@segment/analytics-next/src/core/analytics/index.ts","../node_modules/@segment/analytics-next/src/plugins/env-enrichment/index.ts","../node_modules/@segment/analytics-next/src/lib/client-hints/index.ts","../node_modules/@segment/analytics-next/src/plugins/remote-loader/index.ts","../node_modules/@segment/analytics-next/src/lib/on-page-change.ts","../node_modules/@segment/analytics-next/src/plugins/segmentio/batched-dispatcher.ts","../node_modules/@segment/analytics-next/src/plugins/segmentio/normalize.ts","../node_modules/@segment/analytics-next/src/plugins/segmentio/schedule-flush.ts","../node_modules/@segment/analytics-next/src/plugins/segmentio/index.ts","../node_modules/@segment/analytics-next/src/plugins/segmentio/fetch-dispatcher.ts","../node_modules/@segment/analytics-next/src/core/inspector/index.ts","../node_modules/@segment/analytics-next/src/browser/index.ts","segmentAnalytics.js","components/Dashboard/Header.js","../node_modules/@propelauth/react/src/hooks/useLogoutFunction.ts","../node_modules/@propelauth/react/src/hooks/useHostedPageUrls.tsx","../node_modules/@mui/material/Card/cardClasses.js","../node_modules/@mui/material/Card/Card.js","../node_modules/@mui/material/CardContent/cardContentClasses.js","../node_modules/@mui/material/CardContent/CardContent.js","../node_modules/@mui/system/esm/useThemeProps/useThemeProps.js","../node_modules/@mui/system/esm/useThemeProps/getThemeProps.js","../node_modules/@mui/material/styles/useThemeProps.js","../node_modules/@mui/material/Grid/GridContext.js","../node_modules/@mui/material/Grid/gridClasses.js","../node_modules/@mui/material/Grid/Grid.js","../node_modules/@mui/icons-material/esm/Phone.js","../node_modules/@mui/icons-material/esm/Group.js","components/Dashboard/RecentSimulations.js","../node_modules/@mui/system/esm/styled/styled.js","../node_modules/@mui/system/esm/Grid/traverseBreakpoints.js","../node_modules/@mui/system/esm/Grid/gridGenerator.js","../node_modules/@mui/system/esm/Grid/createGrid.js","../node_modules/@mui/material/Grid2/Grid2.js","../node_modules/@popperjs/core/lib/dom-utils/getWindow.js","../node_modules/@popperjs/core/lib/dom-utils/instanceOf.js","../node_modules/@popperjs/core/lib/utils/math.js","../node_modules/@popperjs/core/lib/utils/userAgent.js","../node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js","../node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js","../node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js","../node_modules/@popperjs/core/lib/dom-utils/getNodeName.js","../node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js","../node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js","../node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js","../node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js","../node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js","../node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js","../node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js","../node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js","../node_modules/@popperjs/core/lib/dom-utils/getParentNode.js","../node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js","../node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js","../node_modules/@popperjs/core/lib/dom-utils/isTableElement.js","../node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js","../node_modules/@popperjs/core/lib/enums.js","../node_modules/@popperjs/core/lib/utils/orderModifiers.js","../node_modules/@popperjs/core/lib/utils/debounce.js","../node_modules/@popperjs/core/lib/createPopper.js","../node_modules/@popperjs/core/lib/utils/mergeByName.js","../node_modules/@popperjs/core/lib/modifiers/eventListeners.js","../node_modules/@popperjs/core/lib/utils/getBasePlacement.js","../node_modules/@popperjs/core/lib/utils/getVariation.js","../node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js","../node_modules/@popperjs/core/lib/utils/computeOffsets.js","../node_modules/@popperjs/core/lib/modifiers/computeStyles.js","../node_modules/@popperjs/core/lib/modifiers/applyStyles.js","../node_modules/@popperjs/core/lib/modifiers/offset.js","../node_modules/@popperjs/core/lib/utils/getOppositePlacement.js","../node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js","../node_modules/@popperjs/core/lib/dom-utils/contains.js","../node_modules/@popperjs/core/lib/utils/rectToClientRect.js","../node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js","../node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js","../node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js","../node_modules/@popperjs/core/lib/utils/mergePaddingObject.js","../node_modules/@popperjs/core/lib/utils/getFreshSideObject.js","../node_modules/@popperjs/core/lib/utils/expandToHashMap.js","../node_modules/@popperjs/core/lib/utils/detectOverflow.js","../node_modules/@popperjs/core/lib/modifiers/flip.js","../node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js","../node_modules/@popperjs/core/lib/utils/within.js","../node_modules/@popperjs/core/lib/modifiers/preventOverflow.js","../node_modules/@popperjs/core/lib/utils/getAltAxis.js","../node_modules/@popperjs/core/lib/modifiers/arrow.js","../node_modules/@popperjs/core/lib/modifiers/hide.js","../node_modules/@popperjs/core/lib/popper.js","../node_modules/@popperjs/core/lib/modifiers/popperOffsets.js","../node_modules/@mui/material/Popper/popperClasses.js","../node_modules/@mui/material/Popper/BasePopper.js","../node_modules/@mui/material/Popper/Popper.js","../node_modules/@mui/material/utils/useId.js","../node_modules/@mui/utils/esm/useControlled/useControlled.js","../node_modules/@mui/material/utils/useControlled.js","../node_modules/@mui/material/Tooltip/tooltipClasses.js","../node_modules/@mui/material/Tooltip/Tooltip.js","components/Dashboard/SimulationTypeModal.js","../node_modules/@mui/material/TextareaAutosize/TextareaAutosize.js","../node_modules/@mui/material/FormControl/formControlState.js","../node_modules/@mui/material/FormControl/FormControlContext.js","../node_modules/@mui/material/FormControl/useFormControl.js","../node_modules/@mui/material/InputBase/utils.js","../node_modules/@mui/material/InputBase/inputBaseClasses.js","../node_modules/@mui/material/InputBase/InputBase.js","../node_modules/@mui/material/Input/inputClasses.js","../node_modules/@mui/material/Input/Input.js","../node_modules/@mui/material/FilledInput/filledInputClasses.js","../node_modules/@mui/material/FilledInput/FilledInput.js","../node_modules/@mui/material/OutlinedInput/NotchedOutline.js","../node_modules/@mui/material/OutlinedInput/outlinedInputClasses.js","../node_modules/@mui/material/OutlinedInput/OutlinedInput.js","../node_modules/@mui/material/FormLabel/formLabelClasses.js","../node_modules/@mui/material/FormLabel/FormLabel.js","../node_modules/@mui/material/InputLabel/inputLabelClasses.js","../node_modules/@mui/material/InputLabel/InputLabel.js","../node_modules/@mui/material/FormControl/formControlClasses.js","../node_modules/@mui/material/FormControl/FormControl.js","../node_modules/@mui/material/FormHelperText/formHelperTextClasses.js","../node_modules/@mui/material/FormHelperText/FormHelperText.js","../node_modules/@mui/material/NativeSelect/nativeSelectClasses.js","../node_modules/@mui/material/NativeSelect/NativeSelectInput.js","../node_modules/@mui/material/Select/selectClasses.js","../node_modules/@mui/material/Select/SelectInput.js","../node_modules/@mui/material/internal/svg-icons/ArrowDropDown.js","../node_modules/@mui/material/Select/Select.js","../node_modules/@mui/material/TextField/textFieldClasses.js","../node_modules/@mui/material/TextField/TextField.js","../node_modules/@mui/icons-material/esm/Edit.js","components/Dashboard/ProductSummaryReviewModal.js","../node_modules/@mui/material/LinearProgress/linearProgressClasses.js","../node_modules/@mui/material/LinearProgress/LinearProgress.js","../node_modules/@mui/icons-material/esm/TrendingUp.js","../node_modules/@mui/icons-material/esm/TrendingDown.js","../node_modules/@mui/icons-material/esm/Info.js","../node_modules/@kurkle/color/dist/color.esm.js","../node_modules/chart.js/src/helpers/helpers.core.ts","../node_modules/chart.js/src/helpers/helpers.math.ts","../node_modules/chart.js/src/helpers/helpers.collection.ts","../node_modules/chart.js/src/helpers/helpers.extras.ts","../node_modules/chart.js/src/helpers/helpers.easing.ts","../node_modules/chart.js/src/helpers/helpers.color.ts","../node_modules/chart.js/src/core/core.animations.defaults.js","../node_modules/chart.js/src/helpers/helpers.intl.ts","../node_modules/chart.js/src/core/core.ticks.js","../node_modules/chart.js/src/core/core.defaults.js","../node_modules/chart.js/src/core/core.layouts.defaults.js","../node_modules/chart.js/src/core/core.scale.defaults.js","../node_modules/chart.js/src/helpers/helpers.canvas.ts","../node_modules/chart.js/src/helpers/helpers.options.ts","../node_modules/chart.js/src/helpers/helpers.config.ts","../node_modules/chart.js/src/helpers/helpers.curve.ts","../node_modules/chart.js/src/helpers/helpers.dom.ts","../node_modules/chart.js/src/helpers/helpers.interpolation.ts","../node_modules/chart.js/src/helpers/helpers.rtl.ts","../node_modules/chart.js/src/helpers/helpers.segment.js","../node_modules/chart.js/src/core/core.animator.js","../node_modules/chart.js/src/core/core.animation.js","../node_modules/chart.js/src/core/core.animations.js","../node_modules/chart.js/src/core/core.datasetController.js","../node_modules/chart.js/src/controllers/controller.bar.js","../node_modules/chart.js/src/controllers/controller.bubble.js","../node_modules/chart.js/src/controllers/controller.doughnut.js","../node_modules/chart.js/src/controllers/controller.line.js","../node_modules/chart.js/src/controllers/controller.polarArea.js","../node_modules/chart.js/src/controllers/controller.pie.js","../node_modules/chart.js/src/controllers/controller.radar.js","../node_modules/chart.js/src/controllers/controller.scatter.js","../node_modules/chart.js/src/core/core.adapters.ts","../node_modules/chart.js/src/core/core.interaction.js","../node_modules/chart.js/src/core/core.layouts.js","../node_modules/chart.js/src/platform/platform.base.js","../node_modules/chart.js/src/platform/platform.basic.js","../node_modules/chart.js/src/platform/platform.dom.js","../node_modules/chart.js/src/core/core.element.ts","../node_modules/chart.js/src/core/core.scale.autoskip.js","../node_modules/chart.js/src/core/core.scale.js","../node_modules/chart.js/src/core/core.typedRegistry.js","../node_modules/chart.js/src/core/core.registry.js","../node_modules/chart.js/src/core/core.plugins.js","../node_modules/chart.js/src/core/core.config.js","../node_modules/chart.js/src/core/core.controller.js","../node_modules/chart.js/src/platform/index.js","../node_modules/chart.js/src/elements/element.arc.ts","../node_modules/chart.js/src/elements/element.line.js","../node_modules/chart.js/src/elements/element.point.ts","../node_modules/chart.js/src/elements/element.bar.js","../node_modules/chart.js/src/plugins/plugin.legend.js","../node_modules/chart.js/src/plugins/plugin.title.js","../node_modules/chart.js/src/plugins/plugin.subtitle.js","../node_modules/chart.js/src/plugins/plugin.tooltip.js","../node_modules/chart.js/src/scales/scale.category.js","../node_modules/chart.js/src/scales/scale.linearbase.js","../node_modules/chart.js/src/scales/scale.linear.js","../node_modules/chart.js/src/scales/scale.logarithmic.js","../node_modules/chart.js/src/scales/scale.radialLinear.js","../node_modules/chart.js/src/scales/scale.time.js","../node_modules/chart.js/src/scales/scale.timeseries.js","../node_modules/react-chartjs-2/src/utils.ts","../node_modules/react-chartjs-2/src/chart.tsx","../node_modules/react-chartjs-2/src/typedCharts.tsx","components/Dashboard/PerformanceOverview.js","../node_modules/@mui/icons-material/esm/School.js","../node_modules/@mui/icons-material/esm/Work.js","../node_modules/@mui/icons-material/esm/EmojiEvents.js","components/Dashboard/DifficultySelectionModal.js","components/Dashboard/CreditCheckModal.js","../node_modules/@mui/material/Stepper/stepperClasses.js","../node_modules/@mui/material/Stepper/StepperContext.js","../node_modules/@mui/material/Step/StepContext.js","../node_modules/@mui/material/StepConnector/stepConnectorClasses.js","../node_modules/@mui/material/StepConnector/StepConnector.js","../node_modules/@mui/material/Stepper/Stepper.js","../node_modules/@mui/material/Step/stepClasses.js","../node_modules/@mui/material/Step/Step.js","../node_modules/@mui/material/internal/svg-icons/CheckCircle.js","../node_modules/@mui/material/internal/svg-icons/Warning.js","../node_modules/@mui/material/StepIcon/stepIconClasses.js","../node_modules/@mui/material/StepIcon/StepIcon.js","../node_modules/@mui/material/StepLabel/stepLabelClasses.js","../node_modules/@mui/material/StepLabel/StepLabel.js","components/Profile/ProductSummaryStep.js","shared/constants/profileConstants.js","components/Profile/IndustryStep.js","../node_modules/@mui/material/internal/svg-icons/Cancel.js","../node_modules/@mui/material/Chip/chipClasses.js","../node_modules/@mui/material/Chip/Chip.js","../node_modules/@mui/material/internal/switchBaseClasses.js","../node_modules/@mui/material/internal/SwitchBase.js","../node_modules/@mui/material/internal/svg-icons/CheckBoxOutlineBlank.js","../node_modules/@mui/material/internal/svg-icons/CheckBox.js","../node_modules/@mui/material/internal/svg-icons/IndeterminateCheckBox.js","../node_modules/@mui/material/Checkbox/checkboxClasses.js","../node_modules/@mui/material/Checkbox/Checkbox.js","components/Profile/TargetCustomerStep/CompanySizeSelect.js","components/Profile/TargetCustomerStep/DecisionMakerLevelSelect.js","components/Profile/TargetCustomerStep/DepartmentSelect.js","logger.js","components/Profile/TargetCustomerStep.js","../node_modules/@mui/material/FormGroup/formGroupClasses.js","../node_modules/@mui/material/FormGroup/FormGroup.js","../node_modules/@mui/material/RadioGroup/radioGroupClasses.js","../node_modules/@mui/material/RadioGroup/RadioGroupContext.js","../node_modules/@mui/material/RadioGroup/RadioGroup.js","../node_modules/@mui/material/FormControlLabel/formControlLabelClasses.js","../node_modules/@mui/material/FormControlLabel/FormControlLabel.js","../node_modules/@mui/material/internal/svg-icons/RadioButtonUnchecked.js","../node_modules/@mui/material/internal/svg-icons/RadioButtonChecked.js","../node_modules/@mui/material/Radio/RadioButtonIcon.js","../node_modules/@mui/material/utils/createChainedFunction.js","../node_modules/@mui/material/Radio/radioClasses.js","../node_modules/@mui/material/Radio/Radio.js","../node_modules/@mui/material/RadioGroup/useRadioGroup.js","components/Profile/GeographicFocusStep.js","components/Profile/CustomizedObjectionsStep.js","components/Profile/ProfileSetupModal.js","components/Dashboard/PersonaProfileSelection.js","components/Dashboard/ProductSummaryModal.js","../node_modules/axios/lib/helpers/bind.js","../node_modules/axios/lib/utils.js","../node_modules/axios/lib/core/AxiosError.js","../node_modules/axios/lib/helpers/toFormData.js","../node_modules/axios/lib/helpers/AxiosURLSearchParams.js","../node_modules/axios/lib/helpers/buildURL.js","../node_modules/axios/lib/core/InterceptorManager.js","../node_modules/axios/lib/defaults/transitional.js","../node_modules/axios/lib/platform/browser/index.js","../node_modules/axios/lib/platform/browser/classes/URLSearchParams.js","../node_modules/axios/lib/platform/browser/classes/FormData.js","../node_modules/axios/lib/platform/browser/classes/Blob.js","../node_modules/axios/lib/platform/common/utils.js","../node_modules/axios/lib/platform/index.js","../node_modules/axios/lib/helpers/formDataToJSON.js","../node_modules/axios/lib/defaults/index.js","../node_modules/axios/lib/helpers/toURLEncodedForm.js","../node_modules/axios/lib/helpers/parseHeaders.js","../node_modules/axios/lib/core/AxiosHeaders.js","../node_modules/axios/lib/core/transformData.js","../node_modules/axios/lib/cancel/isCancel.js","../node_modules/axios/lib/cancel/CanceledError.js","../node_modules/axios/lib/core/settle.js","../node_modules/axios/lib/helpers/speedometer.js","../node_modules/axios/lib/helpers/throttle.js","../node_modules/axios/lib/helpers/progressEventReducer.js","../node_modules/axios/lib/helpers/isURLSameOrigin.js","../node_modules/axios/lib/helpers/cookies.js","../node_modules/axios/lib/core/buildFullPath.js","../node_modules/axios/lib/helpers/isAbsoluteURL.js","../node_modules/axios/lib/helpers/combineURLs.js","../node_modules/axios/lib/core/mergeConfig.js","../node_modules/axios/lib/helpers/resolveConfig.js","../node_modules/axios/lib/adapters/xhr.js","../node_modules/axios/lib/helpers/parseProtocol.js","../node_modules/axios/lib/helpers/composeSignals.js","../node_modules/axios/lib/helpers/trackStream.js","../node_modules/axios/lib/adapters/fetch.js","../node_modules/axios/lib/adapters/adapters.js","../node_modules/axios/lib/helpers/null.js","../node_modules/axios/lib/core/dispatchRequest.js","../node_modules/axios/lib/env/data.js","../node_modules/axios/lib/helpers/validator.js","../node_modules/axios/lib/core/Axios.js","../node_modules/axios/lib/cancel/CancelToken.js","../node_modules/axios/lib/helpers/HttpStatusCode.js","../node_modules/axios/lib/axios.js","../node_modules/axios/lib/helpers/spread.js","../node_modules/axios/lib/helpers/isAxiosError.js","components/Dashboard/InviteDialog.js","components/Dashboard/InviteCTA.js","../node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseBase.js","../node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseKey.js","services/internal/personaService.js","managers/personaManager.js","components/Dashboard/MainContent.js","components/Dashboard/ProfileSummary.js","../node_modules/@mui/icons-material/esm/Person.js","components/Simulation/LoadingScreen.js","../node_modules/@mui/material/CardActions/cardActionsClasses.js","../node_modules/@mui/material/CardActions/CardActions.js","../node_modules/@mui/icons-material/esm/AllInclusive.js","../node_modules/@stripe/stripe-js/dist/index.mjs","services/stripeService.js","components/Dashboard/UpgradeModal.js","components/Dashboard/Dashboard.js","../node_modules/@mui/system/esm/Container/createContainer.js","../node_modules/@mui/material/Container/Container.js","../node_modules/@mui/material/internal/animate.js","../node_modules/@mui/material/Tabs/ScrollbarSize.js","../node_modules/@mui/material/internal/svg-icons/KeyboardArrowLeft.js","../node_modules/@mui/material/internal/svg-icons/KeyboardArrowRight.js","../node_modules/@mui/material/TabScrollButton/tabScrollButtonClasses.js","../node_modules/@mui/material/TabScrollButton/TabScrollButton.js","../node_modules/@mui/material/Tabs/tabsClasses.js","../node_modules/@mui/material/Tabs/Tabs.js","../node_modules/@mui/material/Tab/tabClasses.js","../node_modules/@mui/material/Tab/Tab.js","../node_modules/@mui/material/Collapse/collapseClasses.js","../node_modules/@mui/material/Collapse/Collapse.js","../node_modules/@mui/material/Accordion/AccordionContext.js","../node_modules/@mui/material/Accordion/accordionClasses.js","../node_modules/@mui/material/Accordion/Accordion.js","../node_modules/@mui/material/AccordionSummary/accordionSummaryClasses.js","../node_modules/@mui/material/AccordionSummary/AccordionSummary.js","../node_modules/@mui/material/AccordionDetails/accordionDetailsClasses.js","../node_modules/@mui/material/AccordionDetails/AccordionDetails.js","../node_modules/@mui/icons-material/esm/ExpandMore.js","../node_modules/@mui/icons-material/esm/Business.js","../node_modules/@mui/icons-material/esm/Save.js","components/Simulation/PersonaDisplay.js","components/Simulation/PersonaInfoPanel.js","../node_modules/@mui/icons-material/esm/VolumeUp.js","../node_modules/@mui/icons-material/esm/HelpOutline.js","components/Simulation/PreCallDisplay.js","components/Simulation/MainConversationArea.js","components/Simulation/CallInfoPanel.js","../node_modules/@mui/icons-material/esm/CallEnd.js","../node_modules/@mui/icons-material/esm/Mic.js","../node_modules/@mui/icons-material/esm/MicOff.js","components/Simulation/ControlBar.js","components/Simulation/CallEndingScreen.js","services/vapiService.js","components/Simulation/CountdownDialog.js","../node_modules/@mui/icons-material/esm/Flag.js","../node_modules/@mui/icons-material/esm/Lightbulb.js","../node_modules/@mui/icons-material/esm/FormatListNumbered.js","../node_modules/@mui/icons-material/esm/CheckCircleOutline.js","components/Simulation/HelpDialog.js","services/creditService.js","components/Simulation/SimulationPage.js","utils/vapiAssistantConfigGenerator.js","../node_modules/@mui/material/ListItemButton/ListItemButton.js","../node_modules/@mui/icons-material/esm/Score.js","../node_modules/@mui/icons-material/esm/Analytics.js","../node_modules/@mui/icons-material/esm/Audiotrack.js","components/CallReview/NavigationSidebar.js","components/CallReview/Scorecard.js","components/CallReview/ScoreCardHeader.js","../node_modules/@mui/icons-material/esm/ErrorOutline.js","components/CallReview/PersonaInfo.js","components/CallReview/DetailedAnalysis.js","../node_modules/@mui/utils/esm/visuallyHidden/visuallyHidden.js","../node_modules/@mui/material/utils/areArraysEqual.js","../node_modules/@mui/material/Slider/useSlider.js","../node_modules/@mui/material/utils/shouldSpreadAdditionalProps.js","../node_modules/@mui/material/Slider/sliderClasses.js","../node_modules/@mui/material/Slider/Slider.js","../node_modules/@mui/material/Slider/SliderValueLabel.js","../node_modules/@mui/icons-material/esm/Pause.js","../node_modules/@mui/icons-material/esm/FastForward.js","../node_modules/@mui/icons-material/esm/FastRewind.js","../node_modules/@mui/icons-material/esm/Download.js","../node_modules/@mui/icons-material/esm/Search.js","components/CallReview/TranscriptAndAudio.js","hooks/useCallReviewData.js","components/CallReview/CallReviewPage.js","../node_modules/@mui/material/Table/TableContext.js","../node_modules/@mui/material/Table/Tablelvl2Context.js","../node_modules/@mui/material/TableCell/tableCellClasses.js","../node_modules/@mui/material/TableCell/TableCell.js","../node_modules/@mui/material/TableRow/tableRowClasses.js","../node_modules/@mui/material/TableRow/TableRow.js","../node_modules/@mui/material/TableContainer/tableContainerClasses.js","../node_modules/@mui/material/TableContainer/TableContainer.js","../node_modules/@mui/material/Table/tableClasses.js","../node_modules/@mui/material/Table/Table.js","../node_modules/@mui/material/TableHead/tableHeadClasses.js","../node_modules/@mui/material/TableHead/TableHead.js","../node_modules/@mui/material/internal/svg-icons/ArrowDownward.js","../node_modules/@mui/material/TableSortLabel/tableSortLabelClasses.js","../node_modules/@mui/material/TableSortLabel/TableSortLabel.js","../node_modules/@mui/material/TableBody/tableBodyClasses.js","../node_modules/@mui/material/TableBody/TableBody.js","../node_modules/@mui/material/internal/svg-icons/LastPage.js","../node_modules/@mui/material/internal/svg-icons/FirstPage.js","../node_modules/@mui/material/TablePagination/TablePaginationActions.js","../node_modules/@mui/material/TablePagination/tablePaginationClasses.js","../node_modules/@mui/material/TablePagination/TablePagination.js","components/Dashboard/SimulationHistory.js","../node_modules/@mui/private-theming/useTheme/ThemeContext.js","../node_modules/@mui/private-theming/useTheme/useTheme.js","../node_modules/@mui/private-theming/ThemeProvider/nested.js","../node_modules/@mui/private-theming/ThemeProvider/ThemeProvider.js","../node_modules/@mui/system/esm/ThemeProvider/ThemeProvider.js","../node_modules/@mui/material/styles/ThemeProviderNoVars.js","../node_modules/@mui/system/esm/InitColorSchemeScript/InitColorSchemeScript.js","../node_modules/@mui/system/esm/cssVars/useCurrentColorScheme.js","../node_modules/@mui/material/InitColorSchemeScript/InitColorSchemeScript.js","../node_modules/@mui/material/styles/ThemeProviderWithVars.js","../node_modules/@mui/system/esm/cssVars/createCssVarsProvider.js","../node_modules/@mui/material/styles/ThemeProvider.js","components/Dashboard/CheckoutSuccess.js","../node_modules/@mui/material/Slide/Slide.js","../node_modules/@mui/material/Drawer/drawerClasses.js","../node_modules/@mui/material/Drawer/Drawer.js","../node_modules/@mui/icons-material/esm/Menu.js","../node_modules/@mui/icons-material/esm/ArrowBack.js","components/AdminDashboard/AdminDashboard.js","../node_modules/@mui/icons-material/esm/KeyboardArrowUp.js","../node_modules/@mui/icons-material/esm/KeyboardArrowDown.js","../node_modules/@mui/icons-material/esm/CheckCircle.js","components/AdminDashboard/TeamOverview.js","../node_modules/@mui/icons-material/esm/CalendarToday.js","../node_modules/@mui/icons-material/esm/Speed.js","../node_modules/recharts/es6/util/DataUtils.js","../node_modules/recharts/es6/util/LogUtils.js","../node_modules/recharts/es6/util/ShallowEqual.js","../node_modules/recharts/es6/util/types.js","../node_modules/recharts/es6/util/ReactUtils.js","../node_modules/recharts/es6/component/ResponsiveContainer.js","../node_modules/tiny-invariant/dist/esm/tiny-invariant.js","../node_modules/recharts/es6/container/Surface.js","../node_modules/recharts/es6/container/Layer.js","../node_modules/recharts/es6/component/DefaultTooltipContent.js","../node_modules/recharts/es6/util/tooltip/translate.js","../node_modules/recharts/es6/component/TooltipBoundingBox.js","../node_modules/recharts/es6/util/Global.js","../node_modules/recharts/es6/util/payload/getUniqPayload.js","../node_modules/recharts/es6/component/Tooltip.js","../node_modules/d3-shape/src/math.js","../node_modules/d3-shape/src/symbol/circle.js","../node_modules/d3-shape/src/symbol/cross.js","../node_modules/d3-shape/src/symbol/diamond.js","../node_modules/d3-shape/src/symbol/square.js","../node_modules/d3-shape/src/symbol/star.js","../node_modules/d3-shape/src/symbol/triangle.js","../node_modules/d3-shape/src/symbol/wye.js","../node_modules/d3-shape/src/constant.js","../node_modules/d3-path/src/path.js","../node_modules/d3-shape/src/path.js","../node_modules/d3-shape/src/symbol/asterisk.js","../node_modules/d3-shape/src/symbol/triangle2.js","../node_modules/recharts/es6/shape/Symbols.js","../node_modules/d3-shape/src/symbol.js","../node_modules/recharts/es6/component/DefaultLegendContent.js","../node_modules/recharts/es6/component/Legend.js","../node_modules/recharts/es6/shape/Dot.js","../node_modules/fast-equals/src/utils.ts","../node_modules/fast-equals/src/equals.ts","../node_modules/fast-equals/src/comparator.ts","../node_modules/fast-equals/src/index.ts","../node_modules/react-smooth/es6/setRafTimeout.js","../node_modules/react-smooth/es6/AnimateManager.js","../node_modules/react-smooth/es6/util.js","../node_modules/react-smooth/es6/easing.js","../node_modules/react-smooth/es6/configUpdate.js","../node_modules/react-smooth/es6/Animate.js","../node_modules/react-smooth/es6/AnimateGroupChild.js","../node_modules/react-smooth/es6/AnimateGroup.js","../node_modules/react-smooth/es6/index.js","../node_modules/recharts/es6/shape/Rectangle.js","../node_modules/d3-scale/src/init.js","../node_modules/internmap/src/index.js","../node_modules/d3-scale/src/ordinal.js","../node_modules/d3-scale/src/band.js","../node_modules/d3-array/src/range.js","../node_modules/recharts/es6/util/DOMUtils.js","../node_modules/recharts/es6/util/ReduceCSSCalc.js","../node_modules/recharts/es6/component/Text.js","../node_modules/d3-array/src/ticks.js","../node_modules/d3-array/src/ascending.js","../node_modules/d3-array/src/descending.js","../node_modules/d3-array/src/bisector.js","../node_modules/d3-array/src/number.js","../node_modules/d3-array/src/bisect.js","../node_modules/d3-color/src/define.js","../node_modules/d3-color/src/color.js","../node_modules/d3-interpolate/src/basis.js","../node_modules/d3-interpolate/src/constant.js","../node_modules/d3-interpolate/src/color.js","../node_modules/d3-interpolate/src/rgb.js","../node_modules/d3-interpolate/src/basisClosed.js","../node_modules/d3-interpolate/src/array.js","../node_modules/d3-interpolate/src/date.js","../node_modules/d3-interpolate/src/number.js","../node_modules/d3-interpolate/src/object.js","../node_modules/d3-interpolate/src/string.js","../node_modules/d3-interpolate/src/numberArray.js","../node_modules/d3-interpolate/src/value.js","../node_modules/d3-interpolate/src/round.js","../node_modules/d3-scale/src/number.js","../node_modules/d3-scale/src/continuous.js","../node_modules/d3-scale/src/constant.js","../node_modules/d3-format/src/formatSpecifier.js","../node_modules/d3-format/src/formatPrefixAuto.js","../node_modules/d3-format/src/formatDecimal.js","../node_modules/d3-format/src/exponent.js","../node_modules/d3-format/src/formatRounded.js","../node_modules/d3-format/src/formatTypes.js","../node_modules/d3-format/src/identity.js","../node_modules/d3-format/src/locale.js","../node_modules/d3-format/src/defaultLocale.js","../node_modules/d3-format/src/formatGroup.js","../node_modules/d3-format/src/formatNumerals.js","../node_modules/d3-format/src/formatTrim.js","../node_modules/d3-scale/src/tickFormat.js","../node_modules/d3-format/src/precisionPrefix.js","../node_modules/d3-format/src/precisionRound.js","../node_modules/d3-format/src/precisionFixed.js","../node_modules/d3-scale/src/linear.js","../node_modules/d3-scale/src/identity.js","../node_modules/d3-scale/src/nice.js","../node_modules/d3-scale/src/log.js","../node_modules/d3-scale/src/symlog.js","../node_modules/d3-scale/src/pow.js","../node_modules/d3-scale/src/radial.js","../node_modules/d3-array/src/max.js","../node_modules/d3-array/src/min.js","../node_modules/d3-array/src/sort.js","../node_modules/d3-array/src/quickselect.js","../node_modules/d3-array/src/quantile.js","../node_modules/d3-scale/src/quantile.js","../node_modules/d3-scale/src/quantize.js","../node_modules/d3-scale/src/threshold.js","../node_modules/d3-time/src/duration.js","../node_modules/d3-time/src/interval.js","../node_modules/d3-time/src/millisecond.js","../node_modules/d3-time/src/second.js","../node_modules/d3-time/src/minute.js","../node_modules/d3-time/src/hour.js","../node_modules/d3-time/src/day.js","../node_modules/d3-time/src/week.js","../node_modules/d3-time/src/month.js","../node_modules/d3-time/src/year.js","../node_modules/d3-time/src/ticks.js","../node_modules/d3-time-format/src/locale.js","../node_modules/d3-time-format/src/defaultLocale.js","../node_modules/d3-scale/src/time.js","../node_modules/d3-scale/src/utcTime.js","../node_modules/d3-scale/src/sequential.js","../node_modules/d3-scale/src/sequentialQuantile.js","../node_modules/d3-scale/src/diverging.js","../node_modules/d3-interpolate/src/piecewise.js","../node_modules/d3-shape/src/offset/none.js","../node_modules/d3-shape/src/array.js","../node_modules/d3-shape/src/order/none.js","../node_modules/d3-shape/src/stack.js","../node_modules/recharts-scale/es6/util/utils.js","../node_modules/recharts-scale/es6/util/arithmetic.js","../node_modules/recharts-scale/es6/getNiceTickValues.js","../node_modules/recharts/es6/cartesian/ErrorBar.js","../node_modules/recharts/es6/util/getLegendProps.js","../node_modules/recharts/es6/util/ChartUtils.js","../node_modules/d3-shape/src/offset/expand.js","../node_modules/d3-shape/src/offset/silhouette.js","../node_modules/d3-shape/src/offset/wiggle.js","../node_modules/recharts/es6/util/CssPrefixUtils.js","../node_modules/recharts/es6/cartesian/Brush.js","../node_modules/recharts/es6/util/PolarUtils.js","../node_modules/recharts/es6/component/Label.js","../node_modules/recharts/es6/util/IfOverflowMatches.js","../node_modules/recharts/es6/component/Cell.js","../node_modules/recharts/es6/component/LabelList.js","../node_modules/recharts/es6/shape/Trapezoid.js","../node_modules/recharts/es6/shape/Sector.js","../node_modules/recharts/es6/util/ActiveShapeUtils.js","../node_modules/recharts/es6/util/BarUtils.js","../node_modules/recharts/es6/cartesian/Bar.js","../node_modules/recharts/es6/util/CartesianUtils.js","../node_modules/recharts/es6/cartesian/ReferenceDot.js","../node_modules/recharts/es6/util/calculateViewBox.js","../node_modules/recharts/es6/context/chartLayoutContext.js","../node_modules/recharts/es6/cartesian/ReferenceLine.js","../node_modules/recharts/es6/cartesian/ReferenceArea.js","../node_modules/recharts/es6/util/DetectReferenceElementsDomain.js","../node_modules/recharts/es6/util/Events.js","../node_modules/recharts/es6/chart/AccessibilityManager.js","../node_modules/d3-shape/src/noop.js","../node_modules/d3-shape/src/curve/basis.js","../node_modules/d3-shape/src/curve/basisClosed.js","../node_modules/d3-shape/src/curve/basisOpen.js","../node_modules/d3-shape/src/curve/bump.js","../node_modules/d3-shape/src/curve/linearClosed.js","../node_modules/d3-shape/src/curve/linear.js","../node_modules/d3-shape/src/curve/monotone.js","../node_modules/d3-shape/src/curve/natural.js","../node_modules/d3-shape/src/curve/step.js","../node_modules/d3-shape/src/point.js","../node_modules/d3-shape/src/line.js","../node_modules/d3-shape/src/area.js","../node_modules/recharts/es6/shape/Curve.js","../node_modules/recharts/es6/shape/Cross.js","../node_modules/recharts/es6/util/cursor/getRadialCursorPoints.js","../node_modules/recharts/es6/util/cursor/getCursorPoints.js","../node_modules/recharts/es6/component/Cursor.js","../node_modules/recharts/es6/util/cursor/getCursorRectangle.js","../node_modules/recharts/es6/chart/generateCategoricalChart.js","../node_modules/recharts/es6/util/isDomainSpecifiedByUser.js","../node_modules/recharts/es6/cartesian/Line.js","../node_modules/recharts/es6/util/getEveryNthWithCondition.js","../node_modules/recharts/es6/util/TickUtils.js","../node_modules/recharts/es6/cartesian/getTicks.js","../node_modules/recharts/es6/cartesian/getEquidistantTicks.js","../node_modules/recharts/es6/cartesian/CartesianAxis.js","../node_modules/recharts/es6/cartesian/XAxis.js","../node_modules/recharts/es6/cartesian/YAxis.js","../node_modules/recharts/es6/chart/LineChart.js","../node_modules/recharts/es6/cartesian/CartesianGrid.js","components/AdminDashboard/UserDetail.js","../node_modules/@sentry/utils/src/version.ts","../node_modules/@sentry/utils/src/worldwide.ts","../node_modules/@sentry/core/src/carrier.ts","../node_modules/@sentry/utils/src/is.ts","../node_modules/@sentry/utils/src/browser.ts","../node_modules/@sentry/utils/src/debug-build.ts","../node_modules/@sentry/utils/src/logger.ts","../node_modules/@sentry/utils/src/string.ts","../node_modules/@sentry/utils/src/object.ts","../node_modules/@sentry/utils/src/misc.ts","../node_modules/@sentry/utils/src/propagationContext.ts","../node_modules/@sentry/utils/src/time.ts","../node_modules/@sentry/core/src/session.ts","../node_modules/@sentry/core/src/utils/spanOnScope.ts","../node_modules/@sentry/core/src/scope.ts","../node_modules/@sentry/core/src/asyncContext/stackStrategy.ts","../node_modules/@sentry/core/src/defaultScopes.ts","../node_modules/@sentry/core/src/asyncContext/index.ts","../node_modules/@sentry/core/src/currentScopes.ts","../node_modules/@sentry/core/src/semanticAttributes.ts","../node_modules/@sentry/core/src/utils/hasTracingEnabled.ts","../node_modules/@sentry/utils/src/baggage.ts","../node_modules/@sentry/utils/src/tracing.ts","../node_modules/@sentry/core/src/metrics/metric-summary.ts","../node_modules/@sentry/core/src/tracing/spanstatus.ts","../node_modules/@sentry/core/src/utils/spanUtils.ts","../node_modules/@sentry/core/src/constants.ts","../node_modules/@sentry/core/src/tracing/dynamicSamplingContext.ts","../node_modules/@sentry/core/src/debug-build.ts","../node_modules/@sentry/core/src/utils/parseSampleRate.ts","../node_modules/@sentry/core/src/tracing/sentryNonRecordingSpan.ts","../node_modules/@sentry/utils/src/dsn.ts","../node_modules/@sentry/utils/src/stacktrace.ts","../node_modules/@sentry/utils/src/normalize.ts","../node_modules/@sentry/utils/src/memo.ts","../node_modules/@sentry/utils/src/envelope.ts","../node_modules/@sentry/core/src/tracing/measurement.ts","../node_modules/@sentry/core/src/tracing/utils.ts","../node_modules/@sentry/core/src/tracing/sentrySpan.ts","../node_modules/@sentry/core/src/tracing/logSpans.ts","../node_modules/@sentry/core/src/envelope.ts","../node_modules/@sentry/core/src/tracing/trace.ts","../node_modules/@sentry/core/src/tracing/sampling.ts","../node_modules/@sentry/react/src/profiler.tsx","../node_modules/@sentry/react/src/constants.ts","App.js","../node_modules/@sentry/utils/src/syncpromise.ts","../node_modules/@sentry/core/src/eventProcessors.ts","../node_modules/@sentry/core/src/utils/applyScopeDataToEvent.ts","../node_modules/@sentry/core/src/utils/prepareEvent.ts","../node_modules/@sentry/core/src/exports.ts","../node_modules/@sentry/core/src/integration.ts","../node_modules/@sentry/core/src/integrations/inboundfilters.ts","../node_modules/@sentry/core/src/integrations/functiontostring.ts","../node_modules/@sentry/core/src/integrations/dedupe.ts","../node_modules/@sentry/core/src/sdk.ts","../node_modules/@sentry/core/src/api.ts","../node_modules/@sentry/utils/src/supports.ts","../node_modules/@sentry/utils/src/instrument/handlers.ts","../node_modules/@sentry/utils/src/vendor/supportsHistory.ts","../node_modules/@sentry-internal/browser-utils/src/types.ts","../node_modules/@sentry-internal/browser-utils/src/instrument/history.ts","../node_modules/@sentry/utils/src/error.ts","../node_modules/@sentry/core/src/baseclient.ts","../node_modules/@sentry/utils/src/clientreport.ts","../node_modules/@sentry/core/src/utils/sdkMetadata.ts","../node_modules/@sentry/browser/src/debug-build.ts","../node_modules/@sentry/browser/src/eventbuilder.ts","../node_modules/@sentry/browser/src/helpers.ts","../node_modules/@sentry/browser/src/client.ts","../node_modules/@sentry/utils/src/env.ts","../node_modules/@sentry/browser/src/userfeedback.ts","../node_modules/@sentry-internal/browser-utils/src/instrument/dom.ts","../node_modules/@sentry-internal/browser-utils/src/instrument/xhr.ts","../node_modules/@sentry/core/src/breadcrumbs.ts","../node_modules/@sentry/utils/src/instrument/console.ts","../node_modules/@sentry/utils/src/instrument/fetch.ts","../node_modules/@sentry/utils/src/severity.ts","../node_modules/@sentry/utils/src/url.ts","../node_modules/@sentry/browser/src/integrations/breadcrumbs.ts","../node_modules/@sentry/browser/src/integrations/browserapierrors.ts","../node_modules/@sentry/utils/src/instrument/globalError.ts","../node_modules/@sentry/utils/src/instrument/globalUnhandledRejection.ts","../node_modules/@sentry/browser/src/integrations/globalhandlers.ts","../node_modules/@sentry/browser/src/integrations/httpcontext.ts","../node_modules/@sentry/utils/src/aggregate-errors.ts","../node_modules/@sentry/browser/src/integrations/linkederrors.ts","../node_modules/@sentry/browser/src/stack-parsers.ts","../node_modules/@sentry-internal/browser-utils/src/debug-build.ts","../node_modules/@sentry-internal/browser-utils/src/getNativeImplementation.ts","../node_modules/@sentry/utils/src/promisebuffer.ts","../node_modules/@sentry/utils/src/ratelimit.ts","../node_modules/@sentry/core/src/transports/base.ts","../node_modules/@sentry/browser/src/transports/fetch.ts","../node_modules/@sentry/browser/src/sdk.ts","../node_modules/@sentry/utils/src/buildPolyfills/_optionalChain.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/bindReporter.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/getNavigationEntry.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/getActivationStart.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/initMetric.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/generateUniqueID.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/observe.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/onHidden.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/runOnce.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/getVisibilityWatcher.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/whenActivated.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/onFCP.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/getCLS.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/getFID.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/polyfills/interactionCountPolyfill.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/getINP.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/getLCP.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/onTTFB.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/instrument.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/utils.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/cls.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/browserMetrics.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/inp.ts","../node_modules/@sentry/core/src/tracing/idleSpan.ts","../node_modules/@sentry/core/src/tracing/errors.ts","../node_modules/@sentry/core/src/fetch.ts","../node_modules/@sentry/browser/src/tracing/request.ts","../node_modules/@sentry/browser/src/tracing/browserTracingIntegration.ts","../node_modules/@sentry/core/src/utils/isSentryRequestUrl.ts","../node_modules/@sentry/utils/src/node.ts","../node_modules/@sentry/utils/src/isBrowser.ts","../node_modules/@sentry-internal/replay/src/constants.ts","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb-snapshot/es/rrweb-snapshot.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/utils.js","../node_modules/@sentry/utils/src/buildPolyfills/_nullishCoalesce.ts","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/types/dist/rrweb-types.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/mutation.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/error-handler.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observer.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/cross-origin-iframe-mirror.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/iframe-manager.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/shadow-dom-manager.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/canvas-manager.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/stylesheet-manager.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/processed-node-manager.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/index.js","../node_modules/@sentry-internal/replay/src/debug-build.ts","../node_modules/@sentry-internal/replay/src/util/logger.ts","../node_modules/@sentry-internal/replay/src/types/rrweb.ts","../node_modules/@sentry-internal/replay/src/util/timestamp.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/addBreadcrumbEvent.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/domUtils.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/onWindowOpen.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleClick.ts","../node_modules/@sentry-internal/replay/src/util/createBreadcrumb.ts","../node_modules/node_modules/@sentry-internal/rrweb-snapshot/es/rrweb-snapshot.js","../node_modules/@sentry-internal/replay/src/coreHandlers/util/getAttributesToRecord.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleDom.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleKeyboardEvent.ts","../node_modules/@sentry-internal/replay/src/util/createPerformanceEntries.ts","../node_modules/@sentry-internal/replay-worker/build/esm/worker.ts","../node_modules/@sentry-internal/replay/src/eventBuffer/error.ts","../node_modules/@sentry-internal/replay/src/eventBuffer/EventBufferArray.ts","../node_modules/@sentry-internal/replay/src/eventBuffer/WorkerHandler.ts","../node_modules/@sentry-internal/replay/src/eventBuffer/EventBufferCompressionWorker.ts","../node_modules/@sentry-internal/replay/src/eventBuffer/EventBufferProxy.ts","../node_modules/@sentry-internal/replay/src/eventBuffer/index.ts","../node_modules/@sentry-internal/replay-worker/build/esm/index.js","../node_modules/@sentry-internal/replay/src/util/hasSessionStorage.ts","../node_modules/@sentry-internal/replay/src/session/clearSession.ts","../node_modules/@sentry-internal/replay/src/util/isSampled.ts","../node_modules/@sentry-internal/replay/src/session/Session.ts","../node_modules/@sentry-internal/replay/src/session/saveSession.ts","../node_modules/@sentry-internal/replay/src/session/createSession.ts","../node_modules/@sentry-internal/replay/src/util/isExpired.ts","../node_modules/@sentry-internal/replay/src/util/isSessionExpired.ts","../node_modules/@sentry-internal/replay/src/session/shouldRefreshSession.ts","../node_modules/@sentry-internal/replay/src/session/loadOrCreateSession.ts","../node_modules/@sentry-internal/replay/src/session/fetchSession.ts","../node_modules/@sentry-internal/replay/src/util/addEvent.ts","../node_modules/@sentry-internal/replay/src/util/eventUtils.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleAfterSendEvent.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleBeforeSendEvent.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleBreadcrumbs.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleGlobalEvent.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/addFeedbackBreadcrumb.ts","../node_modules/@sentry-internal/replay/src/util/isRrwebError.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/shouldSampleForBufferEvent.ts","../node_modules/@sentry-internal/replay/src/util/createPerformanceSpans.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleHistory.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/addNetworkBreadcrumb.ts","../node_modules/@sentry-internal/replay/src/util/shouldFilterRequest.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/networkUtils.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/fetchUtils.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/xhrUtils.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleNetworkBreadcrumbs.ts","../node_modules/@sentry-internal/replay/src/util/addGlobalListeners.ts","../node_modules/@sentry-internal/replay/src/util/addMemoryEntry.ts","../node_modules/@sentry-internal/replay/src/util/handleRecordingEmit.ts","../node_modules/@sentry-internal/replay/src/util/sendReplayRequest.ts","../node_modules/@sentry-internal/replay/src/util/prepareRecordingData.ts","../node_modules/@sentry-internal/replay/src/util/prepareReplayEvent.ts","../node_modules/@sentry-internal/replay/src/util/createReplayEnvelope.ts","../node_modules/@sentry-internal/replay/src/util/sendReplay.ts","../node_modules/@sentry-internal/replay/src/util/throttle.ts","../node_modules/@sentry-internal/replay/src/replay.ts","../node_modules/@sentry-internal/replay/src/util/debounce.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/performanceObserver.ts","../node_modules/@sentry-internal/replay/src/util/getPrivacyOptions.ts","../node_modules/@sentry-internal/replay/src/integration.ts","../node_modules/@sentry-internal/replay/src/util/maskAttribute.ts","../node_modules/@sentry/react/src/debug-build.ts","../node_modules/@sentry/react/src/error.ts","../node_modules/@sentry/react/src/errorboundary.tsx","index.js","../node_modules/@sentry/react/src/sdk.ts","../node_modules/@sentry/browser/src/tracing/backgroundtab.ts"],"sourceRoot":"","sourcesContent":["function e(e,t){if(null==e)return{};var n,r,i=function(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r=0||(i[n]=e[n]);return i}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function t(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")}function n(e){return n=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&\"function\"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?\"symbol\":typeof e},n(e)}function r(e){var t=function(e,t){if(\"object\"!==n(e)||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t||\"default\");if(\"object\"!==n(i))return i;throw new TypeError(\"@@toPrimitive must return a primitive value.\")}return(\"string\"===t?String:Number)(e)}(e,\"string\");return\"symbol\"===n(t)?t:String(t)}function i(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n0&&a.length>i&&!a.warned){a.warned=!0;var c=new Error(\"Possible EventEmitter memory leak detected. \"+a.length+\" \"+String(t)+\" listeners added. Use emitter.setMaxListeners() to increase limit\");c.name=\"MaxListenersExceededWarning\",c.emitter=e,c.type=t,c.count=a.length,s=c,console&&console.warn&&console.warn(s)}return e}function T(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function P(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=T.bind(r);return i.listener=n,r.wrapFn=i,i}function O(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:\"function\"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n0&&(o=t[0]),o instanceof Error)throw o;var a=new Error(\"Unhandled error.\"+(o?\" (\"+o.message+\")\":\"\"));throw a.context=o,a}var s=i[e];if(void 0===s)return!1;if(\"function\"==typeof s)b(s,this,t);else{var c=s.length,l=j(s,c);for(n=0;n=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1=0;r--)this.removeListener(e,t[r]);return this},k.prototype.listeners=function(e){return O(this,e,!0)},k.prototype.rawListeners=function(e){return O(this,e,!1)},k.listenerCount=function(e,t){return\"function\"==typeof e.listenerCount?e.listenerCount(t):A.call(e,t)},k.prototype.listenerCount=A,k.prototype.eventNames=function(){return this._eventsCount>0?g(this._events):[]};var x=Object.prototype.hasOwnProperty;function I(e,t,n){for(n of e.keys())if(D(n,t))return n}function D(e,t){var n,r,i;if(e===t)return!0;if(e&&t&&(n=e.constructor)===t.constructor){if(n===Date)return e.getTime()===t.getTime();if(n===RegExp)return e.toString()===t.toString();if(n===Array){if((r=e.length)===t.length)for(;r--&&D(e[r],t[r]););return-1===r}if(n===Set){if(e.size!==t.size)return!1;for(r of e){if((i=r)&&\"object\"==typeof i&&!(i=I(t,i)))return!1;if(!t.has(i))return!1}return!0}if(n===Map){if(e.size!==t.size)return!1;for(r of e){if((i=r[0])&&\"object\"==typeof i&&!(i=I(t,i)))return!1;if(!D(r[1],t.get(i)))return!1}return!0}if(n===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(n===DataView){if((r=e.byteLength)===t.byteLength)for(;r--&&e.getInt8(r)===t.getInt8(r););return-1===r}if(ArrayBuffer.isView(e)){if((r=e.byteLength)===t.byteLength)for(;r--&&e[r]===t[r];);return-1===r}if(!n||\"object\"==typeof e){for(n in r=0,e){if(x.call(e,n)&&++r&&!x.call(t,n))return!1;if(!(n in t)||!D(e[n],t[n]))return!1}return Object.keys(t).length===r}}return e!=e&&t!=t}const N={\"Amazon Silk\":\"amazon_silk\",\"Android Browser\":\"android\",Bada:\"bada\",BlackBerry:\"blackberry\",Chrome:\"chrome\",Chromium:\"chromium\",Electron:\"electron\",Epiphany:\"epiphany\",Firefox:\"firefox\",Focus:\"focus\",Generic:\"generic\",\"Google Search\":\"google_search\",Googlebot:\"googlebot\",\"Internet Explorer\":\"ie\",\"K-Meleon\":\"k_meleon\",Maxthon:\"maxthon\",\"Microsoft Edge\":\"edge\",\"MZ Browser\":\"mz\",\"NAVER Whale Browser\":\"naver\",Opera:\"opera\",\"Opera Coast\":\"opera_coast\",PhantomJS:\"phantomjs\",Puffin:\"puffin\",QupZilla:\"qupzilla\",QQ:\"qq\",QQLite:\"qqlite\",Safari:\"safari\",Sailfish:\"sailfish\",\"Samsung Internet for Android\":\"samsung_internet\",SeaMonkey:\"seamonkey\",Sleipnir:\"sleipnir\",Swing:\"swing\",Tizen:\"tizen\",\"UC Browser\":\"uc\",Vivaldi:\"vivaldi\",\"WebOS Browser\":\"webos\",WeChat:\"wechat\",\"Yandex Browser\":\"yandex\",Roku:\"roku\"},F={amazon_silk:\"Amazon Silk\",android:\"Android Browser\",bada:\"Bada\",blackberry:\"BlackBerry\",chrome:\"Chrome\",chromium:\"Chromium\",electron:\"Electron\",epiphany:\"Epiphany\",firefox:\"Firefox\",focus:\"Focus\",generic:\"Generic\",googlebot:\"Googlebot\",google_search:\"Google Search\",ie:\"Internet Explorer\",k_meleon:\"K-Meleon\",maxthon:\"Maxthon\",edge:\"Microsoft Edge\",mz:\"MZ Browser\",naver:\"NAVER Whale Browser\",opera:\"Opera\",opera_coast:\"Opera Coast\",phantomjs:\"PhantomJS\",puffin:\"Puffin\",qupzilla:\"QupZilla\",qq:\"QQ Browser\",qqlite:\"QQ Browser Lite\",safari:\"Safari\",sailfish:\"Sailfish\",samsung_internet:\"Samsung Internet for Android\",seamonkey:\"SeaMonkey\",sleipnir:\"Sleipnir\",swing:\"Swing\",tizen:\"Tizen\",uc:\"UC Browser\",vivaldi:\"Vivaldi\",webos:\"WebOS Browser\",wechat:\"WeChat\",yandex:\"Yandex Browser\"},R={tablet:\"tablet\",mobile:\"mobile\",desktop:\"desktop\",tv:\"tv\"},B={WindowsPhone:\"Windows Phone\",Windows:\"Windows\",MacOS:\"macOS\",iOS:\"iOS\",Android:\"Android\",WebOS:\"WebOS\",BlackBerry:\"BlackBerry\",Bada:\"Bada\",Tizen:\"Tizen\",Linux:\"Linux\",ChromeOS:\"Chrome OS\",PlayStation4:\"PlayStation 4\",Roku:\"Roku\"},U={EdgeHTML:\"EdgeHTML\",Blink:\"Blink\",Trident:\"Trident\",Presto:\"Presto\",Gecko:\"Gecko\",WebKit:\"WebKit\"};class V{static getFirstMatch(e,t){const n=t.match(e);return n&&n.length>0&&n[1]||\"\"}static getSecondMatch(e,t){const n=t.match(e);return n&&n.length>1&&n[2]||\"\"}static matchAndReturnConst(e,t,n){if(e.test(t))return n}static getWindowsVersionName(e){switch(e){case\"NT\":return\"NT\";case\"XP\":case\"NT 5.1\":return\"XP\";case\"NT 5.0\":return\"2000\";case\"NT 5.2\":return\"2003\";case\"NT 6.0\":return\"Vista\";case\"NT 6.1\":return\"7\";case\"NT 6.2\":return\"8\";case\"NT 6.3\":return\"8.1\";case\"NT 10.0\":return\"10\";default:return}}static getMacOSVersionName(e){const t=e.split(\".\").splice(0,2).map((e=>parseInt(e,10)||0));if(t.push(0),10===t[0])switch(t[1]){case 5:return\"Leopard\";case 6:return\"Snow Leopard\";case 7:return\"Lion\";case 8:return\"Mountain Lion\";case 9:return\"Mavericks\";case 10:return\"Yosemite\";case 11:return\"El Capitan\";case 12:return\"Sierra\";case 13:return\"High Sierra\";case 14:return\"Mojave\";case 15:return\"Catalina\";default:return}}static getAndroidVersionName(e){const t=e.split(\".\").splice(0,2).map((e=>parseInt(e,10)||0));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?\"Cupcake\":1===t[0]&&t[1]>=6?\"Donut\":2===t[0]&&t[1]<2?\"Eclair\":2===t[0]&&2===t[1]?\"Froyo\":2===t[0]&&t[1]>2?\"Gingerbread\":3===t[0]?\"Honeycomb\":4===t[0]&&t[1]<1?\"Ice Cream Sandwich\":4===t[0]&&t[1]<4?\"Jelly Bean\":4===t[0]&&t[1]>=4?\"KitKat\":5===t[0]?\"Lollipop\":6===t[0]?\"Marshmallow\":7===t[0]?\"Nougat\":8===t[0]?\"Oreo\":9===t[0]?\"Pie\":void 0}static getVersionPrecision(e){return e.split(\".\").length}static compareVersions(e,t,n=!1){const r=V.getVersionPrecision(e),i=V.getVersionPrecision(t);let o=Math.max(r,i),a=0;const s=V.map([e,t],(e=>{const t=o-V.getVersionPrecision(e),n=e+new Array(t+1).join(\".0\");return V.map(n.split(\".\"),(e=>new Array(20-e.length).join(\"0\")+e)).reverse()}));for(n&&(a=o-Math.min(r,i)),o-=1;o>=a;){if(s[0][o]>s[1][o])return 1;if(s[0][o]===s[1][o]){if(o===a)return 0;o-=1}else if(s[0][o]{n[t]=e[t]}))}}return e}static getBrowserAlias(e){return N[e]}static getBrowserTypeByAlias(e){return F[e]||\"\"}}const J=/version\\/(\\d+(\\.?_?\\d+)+)/i,$=[{test:[/googlebot/i],describe(e){const t={name:\"Googlebot\"},n=V.getFirstMatch(/googlebot\\/(\\d+(\\.\\d+))/i,e)||V.getFirstMatch(J,e);return n&&(t.version=n),t}},{test:[/opera/i],describe(e){const t={name:\"Opera\"},n=V.getFirstMatch(J,e)||V.getFirstMatch(/(?:opera)[\\s/](\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/opr\\/|opios/i],describe(e){const t={name:\"Opera\"},n=V.getFirstMatch(/(?:opr|opios)[\\s/](\\S+)/i,e)||V.getFirstMatch(J,e);return n&&(t.version=n),t}},{test:[/SamsungBrowser/i],describe(e){const t={name:\"Samsung Internet for Android\"},n=V.getFirstMatch(J,e)||V.getFirstMatch(/(?:SamsungBrowser)[\\s/](\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/Whale/i],describe(e){const t={name:\"NAVER Whale Browser\"},n=V.getFirstMatch(J,e)||V.getFirstMatch(/(?:whale)[\\s/](\\d+(?:\\.\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/MZBrowser/i],describe(e){const t={name:\"MZ Browser\"},n=V.getFirstMatch(/(?:MZBrowser)[\\s/](\\d+(?:\\.\\d+)+)/i,e)||V.getFirstMatch(J,e);return n&&(t.version=n),t}},{test:[/focus/i],describe(e){const t={name:\"Focus\"},n=V.getFirstMatch(/(?:focus)[\\s/](\\d+(?:\\.\\d+)+)/i,e)||V.getFirstMatch(J,e);return n&&(t.version=n),t}},{test:[/swing/i],describe(e){const t={name:\"Swing\"},n=V.getFirstMatch(/(?:swing)[\\s/](\\d+(?:\\.\\d+)+)/i,e)||V.getFirstMatch(J,e);return n&&(t.version=n),t}},{test:[/coast/i],describe(e){const t={name:\"Opera Coast\"},n=V.getFirstMatch(J,e)||V.getFirstMatch(/(?:coast)[\\s/](\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/opt\\/\\d+(?:.?_?\\d+)+/i],describe(e){const t={name:\"Opera Touch\"},n=V.getFirstMatch(/(?:opt)[\\s/](\\d+(\\.?_?\\d+)+)/i,e)||V.getFirstMatch(J,e);return n&&(t.version=n),t}},{test:[/yabrowser/i],describe(e){const t={name:\"Yandex Browser\"},n=V.getFirstMatch(/(?:yabrowser)[\\s/](\\d+(\\.?_?\\d+)+)/i,e)||V.getFirstMatch(J,e);return n&&(t.version=n),t}},{test:[/ucbrowser/i],describe(e){const t={name:\"UC Browser\"},n=V.getFirstMatch(J,e)||V.getFirstMatch(/(?:ucbrowser)[\\s/](\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/Maxthon|mxios/i],describe(e){const t={name:\"Maxthon\"},n=V.getFirstMatch(J,e)||V.getFirstMatch(/(?:Maxthon|mxios)[\\s/](\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/epiphany/i],describe(e){const t={name:\"Epiphany\"},n=V.getFirstMatch(J,e)||V.getFirstMatch(/(?:epiphany)[\\s/](\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/puffin/i],describe(e){const t={name:\"Puffin\"},n=V.getFirstMatch(J,e)||V.getFirstMatch(/(?:puffin)[\\s/](\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/sleipnir/i],describe(e){const t={name:\"Sleipnir\"},n=V.getFirstMatch(J,e)||V.getFirstMatch(/(?:sleipnir)[\\s/](\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/k-meleon/i],describe(e){const t={name:\"K-Meleon\"},n=V.getFirstMatch(J,e)||V.getFirstMatch(/(?:k-meleon)[\\s/](\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/micromessenger/i],describe(e){const t={name:\"WeChat\"},n=V.getFirstMatch(/(?:micromessenger)[\\s/](\\d+(\\.?_?\\d+)+)/i,e)||V.getFirstMatch(J,e);return n&&(t.version=n),t}},{test:[/qqbrowser/i],describe(e){const t={name:/qqbrowserlite/i.test(e)?\"QQ Browser Lite\":\"QQ Browser\"},n=V.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\\d+(\\.?_?\\d+)+)/i,e)||V.getFirstMatch(J,e);return n&&(t.version=n),t}},{test:[/msie|trident/i],describe(e){const t={name:\"Internet Explorer\"},n=V.getFirstMatch(/(?:msie |rv:)(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/\\sedg\\//i],describe(e){const t={name:\"Microsoft Edge\"},n=V.getFirstMatch(/\\sedg\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/edg([ea]|ios)/i],describe(e){const t={name:\"Microsoft Edge\"},n=V.getSecondMatch(/edg([ea]|ios)\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/vivaldi/i],describe(e){const t={name:\"Vivaldi\"},n=V.getFirstMatch(/vivaldi\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/seamonkey/i],describe(e){const t={name:\"SeaMonkey\"},n=V.getFirstMatch(/seamonkey\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/sailfish/i],describe(e){const t={name:\"Sailfish\"},n=V.getFirstMatch(/sailfish\\s?browser\\/(\\d+(\\.\\d+)?)/i,e);return n&&(t.version=n),t}},{test:[/silk/i],describe(e){const t={name:\"Amazon Silk\"},n=V.getFirstMatch(/silk\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/phantom/i],describe(e){const t={name:\"PhantomJS\"},n=V.getFirstMatch(/phantomjs\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/slimerjs/i],describe(e){const t={name:\"SlimerJS\"},n=V.getFirstMatch(/slimerjs\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/blackberry|\\bbb\\d+/i,/rim\\stablet/i],describe(e){const t={name:\"BlackBerry\"},n=V.getFirstMatch(J,e)||V.getFirstMatch(/blackberry[\\d]+\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/(web|hpw)[o0]s/i],describe(e){const t={name:\"WebOS Browser\"},n=V.getFirstMatch(J,e)||V.getFirstMatch(/w(?:eb)?[o0]sbrowser\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/bada/i],describe(e){const t={name:\"Bada\"},n=V.getFirstMatch(/dolfin\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/tizen/i],describe(e){const t={name:\"Tizen\"},n=V.getFirstMatch(/(?:tizen\\s?)?browser\\/(\\d+(\\.?_?\\d+)+)/i,e)||V.getFirstMatch(J,e);return n&&(t.version=n),t}},{test:[/qupzilla/i],describe(e){const t={name:\"QupZilla\"},n=V.getFirstMatch(/(?:qupzilla)[\\s/](\\d+(\\.?_?\\d+)+)/i,e)||V.getFirstMatch(J,e);return n&&(t.version=n),t}},{test:[/firefox|iceweasel|fxios/i],describe(e){const t={name:\"Firefox\"},n=V.getFirstMatch(/(?:firefox|iceweasel|fxios)[\\s/](\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/electron/i],describe(e){const t={name:\"Electron\"},n=V.getFirstMatch(/(?:electron)\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/MiuiBrowser/i],describe(e){const t={name:\"Miui\"},n=V.getFirstMatch(/(?:MiuiBrowser)[\\s/](\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/chromium/i],describe(e){const t={name:\"Chromium\"},n=V.getFirstMatch(/(?:chromium)[\\s/](\\d+(\\.?_?\\d+)+)/i,e)||V.getFirstMatch(J,e);return n&&(t.version=n),t}},{test:[/chrome|crios|crmo/i],describe(e){const t={name:\"Chrome\"},n=V.getFirstMatch(/(?:chrome|crios|crmo)\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/GSA/i],describe(e){const t={name:\"Google Search\"},n=V.getFirstMatch(/(?:GSA)\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test(e){const t=!e.test(/like android/i),n=e.test(/android/i);return t&&n},describe(e){const t={name:\"Android Browser\"},n=V.getFirstMatch(J,e);return n&&(t.version=n),t}},{test:[/playstation 4/i],describe(e){const t={name:\"PlayStation 4\"},n=V.getFirstMatch(J,e);return n&&(t.version=n),t}},{test:[/safari|applewebkit/i],describe(e){const t={name:\"Safari\"},n=V.getFirstMatch(J,e);return n&&(t.version=n),t}},{test:[/.*/i],describe(e){const t=-1!==e.search(\"\\\\(\")?/^(.*)\\/(.*)[ \\t]\\((.*)/:/^(.*)\\/(.*) /;return{name:V.getFirstMatch(t,e),version:V.getSecondMatch(t,e)}}}];var q=[{test:[/Roku\\/DVP/],describe(e){const t=V.getFirstMatch(/Roku\\/DVP-(\\d+\\.\\d+)/i,e);return{name:B.Roku,version:t}}},{test:[/windows phone/i],describe(e){const t=V.getFirstMatch(/windows phone (?:os)?\\s?(\\d+(\\.\\d+)*)/i,e);return{name:B.WindowsPhone,version:t}}},{test:[/windows /i],describe(e){const t=V.getFirstMatch(/Windows ((NT|XP)( \\d\\d?.\\d)?)/i,e),n=V.getWindowsVersionName(t);return{name:B.Windows,version:t,versionName:n}}},{test:[/Macintosh(.*?) FxiOS(.*?)\\//],describe(e){const t={name:B.iOS},n=V.getSecondMatch(/(Version\\/)(\\d[\\d.]+)/,e);return n&&(t.version=n),t}},{test:[/macintosh/i],describe(e){const t=V.getFirstMatch(/mac os x (\\d+(\\.?_?\\d+)+)/i,e).replace(/[_\\s]/g,\".\"),n=V.getMacOSVersionName(t),r={name:B.MacOS,version:t};return n&&(r.versionName=n),r}},{test:[/(ipod|iphone|ipad)/i],describe(e){const t=V.getFirstMatch(/os (\\d+([_\\s]\\d+)*) like mac os x/i,e).replace(/[_\\s]/g,\".\");return{name:B.iOS,version:t}}},{test(e){const t=!e.test(/like android/i),n=e.test(/android/i);return t&&n},describe(e){const t=V.getFirstMatch(/android[\\s/-](\\d+(\\.\\d+)*)/i,e),n=V.getAndroidVersionName(t),r={name:B.Android,version:t};return n&&(r.versionName=n),r}},{test:[/(web|hpw)[o0]s/i],describe(e){const t=V.getFirstMatch(/(?:web|hpw)[o0]s\\/(\\d+(\\.\\d+)*)/i,e),n={name:B.WebOS};return t&&t.length&&(n.version=t),n}},{test:[/blackberry|\\bbb\\d+/i,/rim\\stablet/i],describe(e){const t=V.getFirstMatch(/rim\\stablet\\sos\\s(\\d+(\\.\\d+)*)/i,e)||V.getFirstMatch(/blackberry\\d+\\/(\\d+([_\\s]\\d+)*)/i,e)||V.getFirstMatch(/\\bbb(\\d+)/i,e);return{name:B.BlackBerry,version:t}}},{test:[/bada/i],describe(e){const t=V.getFirstMatch(/bada\\/(\\d+(\\.\\d+)*)/i,e);return{name:B.Bada,version:t}}},{test:[/tizen/i],describe(e){const t=V.getFirstMatch(/tizen[/\\s](\\d+(\\.\\d+)*)/i,e);return{name:B.Tizen,version:t}}},{test:[/linux/i],describe:()=>({name:B.Linux})},{test:[/CrOS/],describe:()=>({name:B.ChromeOS})},{test:[/PlayStation 4/],describe(e){const t=V.getFirstMatch(/PlayStation 4[/\\s](\\d+(\\.\\d+)*)/i,e);return{name:B.PlayStation4,version:t}}}],z=[{test:[/googlebot/i],describe:()=>({type:\"bot\",vendor:\"Google\"})},{test:[/huawei/i],describe(e){const t=V.getFirstMatch(/(can-l01)/i,e)&&\"Nova\",n={type:R.mobile,vendor:\"Huawei\"};return t&&(n.model=t),n}},{test:[/nexus\\s*(?:7|8|9|10).*/i],describe:()=>({type:R.tablet,vendor:\"Nexus\"})},{test:[/ipad/i],describe:()=>({type:R.tablet,vendor:\"Apple\",model:\"iPad\"})},{test:[/Macintosh(.*?) FxiOS(.*?)\\//],describe:()=>({type:R.tablet,vendor:\"Apple\",model:\"iPad\"})},{test:[/kftt build/i],describe:()=>({type:R.tablet,vendor:\"Amazon\",model:\"Kindle Fire HD 7\"})},{test:[/silk/i],describe:()=>({type:R.tablet,vendor:\"Amazon\"})},{test:[/tablet(?! pc)/i],describe:()=>({type:R.tablet})},{test(e){const t=e.test(/ipod|iphone/i),n=e.test(/like (ipod|iphone)/i);return t&&!n},describe(e){const t=V.getFirstMatch(/(ipod|iphone)/i,e);return{type:R.mobile,vendor:\"Apple\",model:t}}},{test:[/nexus\\s*[0-6].*/i,/galaxy nexus/i],describe:()=>({type:R.mobile,vendor:\"Nexus\"})},{test:[/[^-]mobi/i],describe:()=>({type:R.mobile})},{test:e=>\"blackberry\"===e.getBrowserName(!0),describe:()=>({type:R.mobile,vendor:\"BlackBerry\"})},{test:e=>\"bada\"===e.getBrowserName(!0),describe:()=>({type:R.mobile})},{test:e=>\"windows phone\"===e.getBrowserName(),describe:()=>({type:R.mobile,vendor:\"Microsoft\"})},{test(e){const t=Number(String(e.getOSVersion()).split(\".\")[0]);return\"android\"===e.getOSName(!0)&&t>=3},describe:()=>({type:R.tablet})},{test:e=>\"android\"===e.getOSName(!0),describe:()=>({type:R.mobile})},{test:e=>\"macos\"===e.getOSName(!0),describe:()=>({type:R.desktop,vendor:\"Apple\"})},{test:e=>\"windows\"===e.getOSName(!0),describe:()=>({type:R.desktop})},{test:e=>\"linux\"===e.getOSName(!0),describe:()=>({type:R.desktop})},{test:e=>\"playstation 4\"===e.getOSName(!0),describe:()=>({type:R.tv})},{test:e=>\"roku\"===e.getOSName(!0),describe:()=>({type:R.tv})}],W=[{test:e=>\"microsoft edge\"===e.getBrowserName(!0),describe(e){if(/\\sedg\\//i.test(e))return{name:U.Blink};const t=V.getFirstMatch(/edge\\/(\\d+(\\.?_?\\d+)+)/i,e);return{name:U.EdgeHTML,version:t}}},{test:[/trident/i],describe(e){const t={name:U.Trident},n=V.getFirstMatch(/trident\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:e=>e.test(/presto/i),describe(e){const t={name:U.Presto},n=V.getFirstMatch(/presto\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test(e){const t=e.test(/gecko/i),n=e.test(/like gecko/i);return t&&!n},describe(e){const t={name:U.Gecko},n=V.getFirstMatch(/gecko\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/(apple)?webkit\\/537\\.36/i],describe:()=>({name:U.Blink})},{test:[/(apple)?webkit/i],describe(e){const t={name:U.WebKit},n=V.getFirstMatch(/webkit\\/(\\d+(\\.?_?\\d+)+)/i,e);return n&&(t.version=n),t}}];class H{constructor(e,t=!1){if(null==e||\"\"===e)throw new Error(\"UserAgent parameter can't be empty\");this._ua=e,this.parsedResult={},!0!==t&&this.parse()}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=V.find($,(e=>{if(\"function\"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error(\"Browser's test function is not valid\")}));return e&&(this.parsedResult.browser=e.describe(this.getUA())),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(e){return e?String(this.getBrowser().name).toLowerCase()||\"\":this.getBrowser().name||\"\"}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const e=V.find(q,(e=>{if(\"function\"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error(\"Browser's test function is not valid\")}));return e&&(this.parsedResult.os=e.describe(this.getUA())),this.parsedResult.os}getOSName(e){const{name:t}=this.getOS();return e?String(t).toLowerCase()||\"\":t||\"\"}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:t}=this.getPlatform();return e?String(t).toLowerCase()||\"\":t||\"\"}parsePlatform(){this.parsedResult.platform={};const e=V.find(z,(e=>{if(\"function\"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error(\"Browser's test function is not valid\")}));return e&&(this.parsedResult.platform=e.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(e){return e?String(this.getEngine().name).toLowerCase()||\"\":this.getEngine().name||\"\"}parseEngine(){this.parsedResult.engine={};const e=V.find(W,(e=>{if(\"function\"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error(\"Browser's test function is not valid\")}));return e&&(this.parsedResult.engine=e.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return V.assign({},this.parsedResult)}satisfies(e){const t={};let n=0;const r={};let i=0;if(Object.keys(e).forEach((o=>{const a=e[o];\"string\"==typeof a?(r[o]=a,i+=1):\"object\"==typeof a&&(t[o]=a,n+=1)})),n>0){const e=Object.keys(t),n=V.find(e,(e=>this.isOS(e)));if(n){const e=this.satisfies(t[n]);if(void 0!==e)return e}const r=V.find(e,(e=>this.isPlatform(e)));if(r){const e=this.satisfies(t[r]);if(void 0!==e)return e}}if(i>0){const e=Object.keys(r),t=V.find(e,(e=>this.isBrowser(e,!0)));if(void 0!==t)return this.compareVersion(r[t])}}isBrowser(e,t=!1){const n=this.getBrowserName().toLowerCase();let r=e.toLowerCase();const i=V.getBrowserTypeByAlias(r);return t&&i&&(r=i.toLowerCase()),r===n}compareVersion(e){let t=[0],n=e,r=!1;const i=this.getBrowserVersion();if(\"string\"==typeof i)return\">\"===e[0]||\"<\"===e[0]?(n=e.substr(1),\"=\"===e[1]?(r=!0,n=e.substr(2)):t=[],\">\"===e[0]?t.push(1):t.push(-1)):\"=\"===e[0]?n=e.substr(1):\"~\"===e[0]&&(r=!0,n=e.substr(1)),t.indexOf(V.compareVersions(i,n,r))>-1}isOS(e){return this.getOSName(!0)===String(e).toLowerCase()}isPlatform(e){return this.getPlatformType(!0)===String(e).toLowerCase()}isEngine(e){return this.getEngineName(!0)===String(e).toLowerCase()}is(e,t=!1){return this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some((e=>this.is(e)))}}\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 */class G{static getParser(e,t=!1){if(\"string\"!=typeof e)throw new Error(\"UserAgent should be a string\");return new H(e,t)}static parse(e){return new H(e).getResult()}static get BROWSER_MAP(){return F}static get ENGINE_MAP(){return U}static get OS_MAP(){return B}static get PLATFORMS_MAP(){return R}}function Q(){return Date.now()+Math.random().toString()}function Y(){throw new Error(\"Method must be implemented in subclass\")}function K(e,t){return null!=t&&t.proxyUrl?t.proxyUrl+(\"/\"===t.proxyUrl.slice(-1)?\"\":\"/\")+e.substring(8):e}function X(e){return null!=e&&e.callObjectBundleUrlOverride?e.callObjectBundleUrlOverride:K(\"https://c.daily.co/call-machine/versioned/\".concat(\"0.75.2\",\"/static/call-machine-object-bundle.js\"),e)}function Z(e){try{new URL(e)}catch(e){return!1}return!0}const ee=Object.prototype.toString;function te(e){switch(ee.call(e)){case\"[object Error]\":case\"[object Exception]\":case\"[object DOMException]\":return!0;default:return de(e,Error)}}function ne(e,t){return ee.call(e)===`[object ${t}]`}function re(e){return ne(e,\"ErrorEvent\")}function ie(e){return ne(e,\"DOMError\")}function oe(e){return ne(e,\"String\")}function ae(e){return\"object\"==typeof e&&null!==e&&\"__sentry_template_string__\"in e&&\"__sentry_template_values__\"in e}function se(e){return null===e||ae(e)||\"object\"!=typeof e&&\"function\"!=typeof e}function ce(e){return ne(e,\"Object\")}function le(e){return\"undefined\"!=typeof Event&&de(e,Event)}function ue(e){return Boolean(e&&e.then&&\"function\"==typeof e.then)}function de(e,t){try{return e instanceof t}catch(e){return!1}}function pe(e){return!(\"object\"!=typeof e||null===e||!e.__isVue&&!e._isVue)}function he(e,t=0){return\"string\"!=typeof e||0===t||e.length<=t?e:`${e.slice(0,t)}...`}function fe(e,t){if(!Array.isArray(e))return\"\";const n=[];for(let t=0;tve(e,t,n)))}function me(e,t,n=250,r,i,o,a){if(!(o.exception&&o.exception.values&&a&&de(a.originalException,Error)))return;const s=o.exception.values.length>0?o.exception.values[o.exception.values.length-1]:void 0;var c,l;s&&(o.exception.values=(c=ye(e,t,i,a.originalException,r,o.exception.values,s,0),l=n,c.map((e=>(e.value&&(e.value=he(e.value,l)),e)))))}function ye(e,t,n,r,i,o,a,s){if(o.length>=n+1)return o;let c=[...o];if(de(r[i],Error)){_e(a,s);const o=e(t,r[i]),l=c.length;be(o,i,l,s),c=ye(e,t,n,r[i],i,[o,...c],o,l)}return Array.isArray(r.errors)&&r.errors.forEach(((r,o)=>{if(de(r,Error)){_e(a,s);const l=e(t,r),u=c.length;be(l,`errors[${o}]`,u,s),c=ye(e,t,n,r,i,[l,...c],l,u)}})),c}function _e(e,t){e.mechanism=e.mechanism||{type:\"generic\",handled:!0},e.mechanism={...e.mechanism,...\"AggregateError\"===e.type&&{is_exception_group:!0},exception_id:t}}function be(e,t,n,r){e.mechanism=e.mechanism||{type:\"generic\",handled:!0},e.mechanism={...e.mechanism,type:\"chained\",source:t,exception_id:n,parent_id:r}}function we(e){return void 0===e?void 0:e>=400&&e<500?\"warning\":e>=500?\"error\":void 0}const ke=\"8.33.1\",Se=globalThis;function Me(e,t,n){const r=n||Se,i=r.__SENTRY__=r.__SENTRY__||{},o=i[ke]=i[ke]||{};return o[e]||(o[e]=t())}const Ce=Se;function Ee(e,t={}){if(!e)return\"\";try{let n=e;const r=5,i=[];let o=0,a=0;const s=\" > \",c=s.length;let l;const u=Array.isArray(t)?t:t.keyAttrs,d=!Array.isArray(t)&&t.maxStringLength||80;for(;n&&o++1&&a+i.length*c+l.length>=d));)i.push(l),a+=l.length,n=n.parentNode;return i.reverse().join(s)}catch(e){return\"\"}}function Te(e,t){const n=e,r=[];if(!n||!n.tagName)return\"\";if(Ce.HTMLElement&&n instanceof HTMLElement&&n.dataset){if(n.dataset.sentryComponent)return n.dataset.sentryComponent;if(n.dataset.sentryElement)return n.dataset.sentryElement}r.push(n.tagName.toLowerCase());const i=t&&t.length?t.filter((e=>n.getAttribute(e))).map((e=>[e,n.getAttribute(e)])):null;if(i&&i.length)i.forEach((e=>{r.push(`[${e[0]}=\"${e[1]}\"]`)}));else{n.id&&r.push(`#${n.id}`);const e=n.className;if(e&&oe(e)){const t=e.split(/\\s+/);for(const e of t)r.push(`.${e}`)}}const o=[\"aria-label\",\"type\",\"name\",\"title\",\"alt\"];for(const e of o){const t=n.getAttribute(e);t&&r.push(`[${e}=\"${t}\"]`)}return r.join(\"\")}const Pe=\"undefined\"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,Oe=[\"debug\",\"info\",\"warn\",\"error\",\"log\",\"assert\",\"trace\"],Ae={};function je(e){if(!(\"console\"in Se))return e();const t=Se.console,n={},r=Object.keys(Ae);r.forEach((e=>{const r=Ae[e];n[e]=t[e],t[e]=r}));try{return e()}finally{r.forEach((e=>{t[e]=n[e]}))}}const Le=Me(\"logger\",(function(){let e=!1;const t={enable:()=>{e=!0},disable:()=>{e=!1},isEnabled:()=>e};return Pe?Oe.forEach((n=>{t[n]=(...t)=>{e&&je((()=>{Se.console[n](`Sentry Logger [${n}]:`,...t)}))}})):Oe.forEach((e=>{t[e]=()=>{}})),t})),xe=/^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;function Ie(e,t=!1){const{host:n,path:r,pass:i,port:o,projectId:a,protocol:s,publicKey:c}=e;return`${s}://${c}${t&&i?`:${i}`:\"\"}@${n}${o?`:${o}`:\"\"}/${r?`${r}/`:r}${a}`}function De(e){return{protocol:e.protocol,publicKey:e.publicKey||\"\",pass:e.pass||\"\",host:e.host,port:e.port||\"\",path:e.path||\"\",projectId:e.projectId}}function Ne(e){const t=\"string\"==typeof e?function(e){const t=xe.exec(e);if(!t)return void je((()=>{console.error(`Invalid Sentry Dsn: ${e}`)}));const[n,r,i=\"\",o=\"\",a=\"\",s=\"\"]=t.slice(1);let c=\"\",l=s;const u=l.split(\"/\");if(u.length>1&&(c=u.slice(0,-1).join(\"/\"),l=u.pop()),l){const e=l.match(/^\\d+/);e&&(l=e[0])}return De({host:o,pass:i,path:c,projectId:l,port:a,protocol:n,publicKey:r})}(e):De(e);if(t&&function(e){if(!Pe)return!0;const{port:t,projectId:n,protocol:r}=e;return!([\"protocol\",\"publicKey\",\"host\",\"projectId\"].find((t=>!e[t]&&(Le.error(`Invalid Sentry Dsn: ${t} missing`),!0)))||(n.match(/^\\d+$/)?function(e){return\"http\"===e||\"https\"===e}(r)?t&&isNaN(parseInt(t,10))&&(Le.error(`Invalid Sentry Dsn: Invalid port ${t}`),1):(Le.error(`Invalid Sentry Dsn: Invalid protocol ${r}`),1):(Le.error(`Invalid Sentry Dsn: Invalid projectId ${n}`),1)))}(t))return t}class Fe extends Error{constructor(e,t=\"warn\"){super(e),this.message=e,this.name=new.target.prototype.constructor.name,Object.setPrototypeOf(this,new.target.prototype),this.logLevel=t}}function Re(e,t,n){if(!(t in e))return;const r=e[t],i=n(r);\"function\"==typeof i&&Ue(i,r),e[t]=i}function Be(e,t,n){try{Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0})}catch(n){Pe&&Le.log(`Failed to add non-enumerable property \"${t}\" to object`,e)}}function Ue(e,t){try{const n=t.prototype||{};e.prototype=t.prototype=n,Be(e,\"__sentry_original__\",t)}catch(e){}}function Ve(e){return e.__sentry_original__}function Je(e){if(te(e))return{message:e.message,name:e.name,stack:e.stack,...qe(e)};if(le(e)){const t={type:e.type,target:$e(e.target),currentTarget:$e(e.currentTarget),...qe(e)};return\"undefined\"!=typeof CustomEvent&&de(e,CustomEvent)&&(t.detail=e.detail),t}return e}function $e(e){try{return t=e,\"undefined\"!=typeof Element&&de(t,Element)?Ee(e):Object.prototype.toString.call(e)}catch(e){return\"\"}var t}function qe(e){if(\"object\"==typeof e&&null!==e){const t={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}return{}}function ze(e){return We(e,new Map)}function We(e,t){if(function(e){if(!ce(e))return!1;try{const t=Object.getPrototypeOf(e).constructor.name;return!t||\"Object\"===t}catch(e){return!0}}(e)){const n=t.get(e);if(void 0!==n)return n;const r={};t.set(e,r);for(const n of Object.getOwnPropertyNames(e))void 0!==e[n]&&(r[n]=We(e[n],t));return r}if(Array.isArray(e)){const n=t.get(e);if(void 0!==n)return n;const r=[];return t.set(e,r),e.forEach((e=>{r.push(We(e,t))})),r}return e}const He=\"?\",Ge=/\\(error: (.*)\\)/,Qe=/captureMessage|captureException/;function Ye(e){return e[e.length-1]||{}}const Ke=\"\";function Xe(e){try{return e&&\"function\"==typeof e&&e.name||Ke}catch(e){return Ke}}function Ze(e){const t=e.exception;if(t){const e=[];try{return t.values.forEach((t=>{t.stacktrace.frames&&e.push(...t.stacktrace.frames)})),e}catch(e){return}}}const et={},tt={};function nt(e,t){et[e]=et[e]||[],et[e].push(t)}function rt(e,t){tt[e]||(t(),tt[e]=!0)}function it(e,t){const n=e&&et[e];if(n)for(const r of n)try{r(t)}catch(t){Pe&&Le.error(`Error while triggering instrumentation handler.\\nType: ${e}\\nName: ${Xe(r)}\\nError:`,t)}}function ot(){\"console\"in Se&&Oe.forEach((function(e){e in Se.console&&Re(Se.console,e,(function(t){return Ae[e]=t,function(...t){it(\"console\",{args:t,level:e});const n=Ae[e];n&&n.apply(Se.console,t)}}))}))}const at=Se;function st(e){return e&&/^function\\s+\\w+\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(e.toString())}function ct(){if(\"string\"==typeof EdgeRuntime)return!0;if(!function(){if(!(\"fetch\"in at))return!1;try{return new Headers,new Request(\"http://www.example.com\"),new Response,!0}catch(e){return!1}}())return!1;if(st(at.fetch))return!0;let e=!1;const t=at.document;if(t&&\"function\"==typeof t.createElement)try{const n=t.createElement(\"iframe\");n.hidden=!0,t.head.appendChild(n),n.contentWindow&&n.contentWindow.fetch&&(e=st(n.contentWindow.fetch)),t.head.removeChild(n)}catch(e){Pe&&Le.warn(\"Could not create sandbox iframe for pure fetch check, bailing to window.fetch: \",e)}return e}function lt(){return Date.now()/1e3}const ut=function(){const{performance:e}=Se;if(!e||!e.now)return lt;const t=Date.now()-e.now(),n=null==e.timeOrigin?t:e.timeOrigin;return()=>(n+e.now())/1e3}();function dt(e,t){const n=\"fetch\";nt(n,e),rt(n,(()=>function(e,t=!1){if(t&&!ct())return;Re(Se,\"fetch\",(function(t){return function(...n){const{method:r,url:i}=function(e){if(0===e.length)return{method:\"GET\",url:\"\"};if(2===e.length){const[t,n]=e;return{url:ht(t),method:pt(n,\"method\")?String(n.method).toUpperCase():\"GET\"}}const t=e[0];return{url:ht(t),method:pt(t,\"method\")?String(t.method).toUpperCase():\"GET\"}}(n),o={args:n,fetchData:{method:r,url:i},startTimestamp:1e3*ut()};e||it(\"fetch\",{...o});const a=(new Error).stack;return t.apply(Se,n).then((async t=>(e?e(t):it(\"fetch\",{...o,endTimestamp:1e3*ut(),response:t}),t)),(e=>{throw it(\"fetch\",{...o,endTimestamp:1e3*ut(),error:e}),te(e)&&void 0===e.stack&&(e.stack=a,Be(e,\"framesToPop\",1)),e}))}}))}(void 0,t)))}function pt(e,t){return!!e&&\"object\"==typeof e&&!!e[t]}function ht(e){return\"string\"==typeof e?e:e?pt(e,\"url\")?e.url:e.toString?e.toString():\"\":\"\"}(()=>{const{performance:e}=Se;if(!e||!e.now)return;const t=36e5,n=e.now(),r=Date.now(),i=e.timeOrigin?Math.abs(e.timeOrigin+n-r):t,o=i16*Math.random();try{if(t&&t.randomUUID)return t.randomUUID().replace(/-/g,\"\");t&&t.getRandomValues&&(n=()=>{const e=new Uint8Array(1);return t.getRandomValues(e),e[0]})}catch(e){}return([1e7]+1e3+4e3+8e3+1e11).replace(/[018]/g,(e=>(e^(15&n())>>e/4).toString(16)))}function _t(e){return e.exception&&e.exception.values?e.exception.values[0]:void 0}function bt(e){const{message:t,event_id:n}=e;if(t)return t;const r=_t(e);return r?r.type&&r.value?`${r.type}: ${r.value}`:r.type||r.value||n||\"\":n||\"\"}function wt(e,t,n){const r=e.exception=e.exception||{},i=r.values=r.values||[],o=i[0]=i[0]||{};o.value||(o.value=t||\"\"),o.type||(o.type=n||\"Error\")}function kt(e,t){const n=_t(e);if(!n)return;const r=n.mechanism;if(n.mechanism={type:\"generic\",handled:!0,...r,...t},t&&\"data\"in t){const e={...r&&r.data,...t.data};n.mechanism.data=e}}function St(e){if(e&&e.__sentry_captured__)return!0;try{Be(e,\"__sentry_captured__\",!0)}catch(e){}return!1}function Mt(e,t=100,n=1/0){try{return Et(\"\",e,t,n)}catch(e){return{ERROR:`**non-serializable** (${e})`}}}function Ct(e,t=3,n=102400){const r=Mt(e,t);return i=r,function(e){return~-encodeURI(e).split(/%..|./).length}(JSON.stringify(i))>n?Ct(e,t-1,n):r;var i}function Et(e,t,n=1/0,r=1/0,i=function(){const e=\"function\"==typeof WeakSet,t=e?new WeakSet:[];return[function(n){if(e)return!!t.has(n)||(t.add(n),!1);for(let e=0;e=r){u[e]=\"[MaxProperties ~]\";break}const t=p[e];u[e]=Et(e,t,c-1,r,i),d++}return a(t),u}var Tt;function Pt(e){return new At((t=>{t(e)}))}function Ot(e){return new At(((t,n)=>{n(e)}))}!function(e){e[e.PENDING=0]=\"PENDING\";e[e.RESOLVED=1]=\"RESOLVED\";e[e.REJECTED=2]=\"REJECTED\"}(Tt||(Tt={}));class At{constructor(e){At.prototype.__init.call(this),At.prototype.__init2.call(this),At.prototype.__init3.call(this),At.prototype.__init4.call(this),this._state=Tt.PENDING,this._handlers=[];try{e(this._resolve,this._reject)}catch(e){this._reject(e)}}then(e,t){return new At(((n,r)=>{this._handlers.push([!1,t=>{if(e)try{n(e(t))}catch(e){r(e)}else n(t)},e=>{if(t)try{n(t(e))}catch(e){r(e)}else r(e)}]),this._executeHandlers()}))}catch(e){return this.then((e=>e),e)}finally(e){return new At(((t,n)=>{let r,i;return this.then((t=>{i=!1,r=t,e&&e()}),(t=>{i=!0,r=t,e&&e()})).then((()=>{i?n(r):t(r)}))}))}__init(){this._resolve=e=>{this._setResult(Tt.RESOLVED,e)}}__init2(){this._reject=e=>{this._setResult(Tt.REJECTED,e)}}__init3(){this._setResult=(e,t)=>{this._state===Tt.PENDING&&(ue(t)?t.then(this._resolve,this._reject):(this._state=e,this._value=t,this._executeHandlers()))}}__init4(){this._executeHandlers=()=>{if(this._state===Tt.PENDING)return;const e=this._handlers.slice();this._handlers=[],e.forEach((e=>{e[0]||(this._state===Tt.RESOLVED&&e[1](this._value),this._state===Tt.REJECTED&&e[2](this._value),e[0]=!0)}))}}}function jt(e){const t=[];function n(e){return t.splice(t.indexOf(e),1)[0]||Promise.resolve(void 0)}return{$:t,add:function(r){if(!(void 0===e||t.lengthn(i))).then(null,(()=>n(i).then(null,(()=>{})))),i},drain:function(e){return new At(((n,r)=>{let i=t.length;if(!i)return n(!0);const o=setTimeout((()=>{e&&e>0&&n(!1)}),e);t.forEach((e=>{Pt(e).then((()=>{--i||(clearTimeout(o),n(!0))}),r)}))}))}}}function Lt(e){if(!e)return{};const t=e.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);if(!t)return{};const n=t[6]||\"\",r=t[8]||\"\";return{host:t[4],path:t[5],protocol:t[2],search:n,hash:r,relative:t[5]+n+r}}const xt=[\"fatal\",\"error\",\"warning\",\"log\",\"info\",\"debug\"];function It(e){return\"warn\"===e?\"warning\":xt.includes(e)?e:\"log\"}const Dt=/^sentry-/;function Nt(e){const t=function(e){if(!e||!oe(e)&&!Array.isArray(e))return;if(Array.isArray(e))return e.reduce(((e,t)=>{const n=Ft(t);return Object.entries(n).forEach((([t,n])=>{e[t]=n})),e}),{});return Ft(e)}(e);if(!t)return;const n=Object.entries(t).reduce(((e,[t,n])=>{if(t.match(Dt)){e[t.slice(7)]=n}return e}),{});return Object.keys(n).length>0?n:void 0}function Ft(e){return e.split(\",\").map((e=>e.split(\"=\").map((e=>decodeURIComponent(e.trim()))))).reduce(((e,[t,n])=>(t&&n&&(e[t]=n),e)),{})}function Rt(e,t=[]){return[e,t]}function Bt(e,t){const[n,r]=e;return[n,[...r,t]]}function Ut(e,t){const n=e[1];for(const e of n){if(t(e,e[0].type))return!0}return!1}function Vt(e){return Se.__SENTRY__&&Se.__SENTRY__.encodePolyfill?Se.__SENTRY__.encodePolyfill(e):(new TextEncoder).encode(e)}function Jt(e){const[t,n]=e;let r=JSON.stringify(t);function i(e){\"string\"==typeof r?r=\"string\"==typeof e?r+e:[Vt(r),e]:r.push(\"string\"==typeof e?Vt(e):e)}for(const e of n){const[t,n]=e;if(i(`\\n${JSON.stringify(t)}\\n`),\"string\"==typeof n||n instanceof Uint8Array)i(n);else{let e;try{e=JSON.stringify(n)}catch(t){e=JSON.stringify(Mt(n))}i(e)}}return\"string\"==typeof r?r:function(e){const t=e.reduce(((e,t)=>e+t.length),0),n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n}(r)}function $t(e){const t=\"string\"==typeof e.data?Vt(e.data):e.data;return[ze({type:\"attachment\",length:t.length,filename:e.filename,content_type:e.contentType,attachment_type:e.attachmentType}),t]}const qt={session:\"session\",sessions:\"session\",attachment:\"attachment\",transaction:\"transaction\",event:\"error\",client_report:\"internal\",user_report:\"default\",profile:\"profile\",profile_chunk:\"profile\",replay_event:\"replay\",replay_recording:\"replay\",check_in:\"monitor\",feedback:\"feedback\",span:\"span\",statsd:\"metric_bucket\"};function zt(e){return qt[e]}function Wt(e){if(!e||!e.sdk)return;const{name:t,version:n}=e.sdk;return{name:t,version:n}}function Ht(e,{statusCode:t,headers:n},r=Date.now()){const i={...e},o=n&&n[\"x-sentry-rate-limits\"],a=n&&n[\"retry-after\"];if(o)for(const e of o.trim().split(\",\")){const[t,n,,,o]=e.split(\":\",5),a=parseInt(t,10),s=1e3*(isNaN(a)?60:a);if(n)for(const e of n.split(\";\"))\"metric_bucket\"===e&&o&&!o.split(\";\").includes(\"custom\")||(i[e]=r+s);else i.all=r+s}else a?i.all=r+function(e,t=Date.now()){const n=parseInt(`${e}`,10);if(!isNaN(n))return 1e3*n;const r=Date.parse(`${e}`);return isNaN(r)?6e4:r-t}(a,r):429===t&&(i.all=r+6e4);return i}function Gt(){return{traceId:yt(),spanId:yt().substring(16)}}const Qt=Se;const Yt=\"undefined\"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__;function Kt(){return Xt(Se),Se}function Xt(e){const t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||ke,t[ke]=t[ke]||{}}function Zt(e,t={}){if(t.user&&(!e.ipAddress&&t.user.ip_address&&(e.ipAddress=t.user.ip_address),e.did||t.did||(e.did=t.user.id||t.user.email||t.user.username)),e.timestamp=t.timestamp||ut(),t.abnormal_mechanism&&(e.abnormal_mechanism=t.abnormal_mechanism),t.ignoreDuration&&(e.ignoreDuration=t.ignoreDuration),t.sid&&(e.sid=32===t.sid.length?t.sid:yt()),void 0!==t.init&&(e.init=t.init),!e.did&&t.did&&(e.did=`${t.did}`),\"number\"==typeof t.started&&(e.started=t.started),e.ignoreDuration)e.duration=void 0;else if(\"number\"==typeof t.duration)e.duration=t.duration;else{const t=e.timestamp-e.started;e.duration=t>=0?t:0}t.release&&(e.release=t.release),t.environment&&(e.environment=t.environment),!e.ipAddress&&t.ipAddress&&(e.ipAddress=t.ipAddress),!e.userAgent&&t.userAgent&&(e.userAgent=t.userAgent),\"number\"==typeof t.errors&&(e.errors=t.errors),t.status&&(e.status=t.status)}const en=\"_sentrySpan\";function tn(e,t){t?Be(e,en,t):delete e[en]}function nn(e){return e[en]}class rn{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext=Gt()}clone(){const e=new rn;return e._breadcrumbs=[...this._breadcrumbs],e._tags={...this._tags},e._extra={...this._extra},e._contexts={...this._contexts},e._user=this._user,e._level=this._level,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[...this._eventProcessors],e._requestSession=this._requestSession,e._attachments=[...this._attachments],e._sdkProcessingMetadata={...this._sdkProcessingMetadata},e._propagationContext={...this._propagationContext},e._client=this._client,e._lastEventId=this._lastEventId,tn(e,nn(this)),e}setClient(e){this._client=e}setLastEventId(e){this._lastEventId=e}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(e){this._scopeListeners.push(e)}addEventProcessor(e){return this._eventProcessors.push(e),this}setUser(e){return this._user=e||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&Zt(this._session,{user:e}),this._notifyScopeListeners(),this}getUser(){return this._user}getRequestSession(){return this._requestSession}setRequestSession(e){return this._requestSession=e,this}setTags(e){return this._tags={...this._tags,...e},this._notifyScopeListeners(),this}setTag(e,t){return this._tags={...this._tags,[e]:t},this._notifyScopeListeners(),this}setExtras(e){return this._extra={...this._extra,...e},this._notifyScopeListeners(),this}setExtra(e,t){return this._extra={...this._extra,[e]:t},this._notifyScopeListeners(),this}setFingerprint(e){return this._fingerprint=e,this._notifyScopeListeners(),this}setLevel(e){return this._level=e,this._notifyScopeListeners(),this}setTransactionName(e){return this._transactionName=e,this._notifyScopeListeners(),this}setContext(e,t){return null===t?delete this._contexts[e]:this._contexts[e]=t,this._notifyScopeListeners(),this}setSession(e){return e?this._session=e:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(e){if(!e)return this;const t=\"function\"==typeof e?e(this):e,[n,r]=t instanceof on?[t.getScopeData(),t.getRequestSession()]:ce(t)?[e,e.requestSession]:[],{tags:i,extra:o,user:a,contexts:s,level:c,fingerprint:l=[],propagationContext:u}=n||{};return this._tags={...this._tags,...i},this._extra={...this._extra,...o},this._contexts={...this._contexts,...s},a&&Object.keys(a).length&&(this._user=a),c&&(this._level=c),l.length&&(this._fingerprint=l),u&&(this._propagationContext=u),r&&(this._requestSession=r),this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._session=void 0,tn(this,void 0),this._attachments=[],this._propagationContext=Gt(),this._notifyScopeListeners(),this}addBreadcrumb(e,t){const n=\"number\"==typeof t?t:100;if(n<=0)return this;const r={timestamp:lt(),...e},i=this._breadcrumbs;return i.push(r),this._breadcrumbs=i.length>n?i.slice(-n):i,this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(e){return this._attachments.push(e),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:nn(this)}}setSDKProcessingMetadata(e){return this._sdkProcessingMetadata={...this._sdkProcessingMetadata,...e},this}setPropagationContext(e){return this._propagationContext=e,this}getPropagationContext(){return this._propagationContext}captureException(e,t){const n=t&&t.event_id?t.event_id:yt();if(!this._client)return Le.warn(\"No client configured on scope - will not capture exception!\"),n;const r=new Error(\"Sentry syntheticException\");return this._client.captureException(e,{originalException:e,syntheticException:r,...t,event_id:n},this),n}captureMessage(e,t,n){const r=n&&n.event_id?n.event_id:yt();if(!this._client)return Le.warn(\"No client configured on scope - will not capture message!\"),r;const i=new Error(e);return this._client.captureMessage(e,t,{originalException:e,syntheticException:i,...n,event_id:r},this),r}captureEvent(e,t){const n=t&&t.event_id?t.event_id:yt();return this._client?(this._client.captureEvent(e,{...t,event_id:n},this),n):(Le.warn(\"No client configured on scope - will not capture event!\"),n)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((e=>{e(this)})),this._notifyingListeners=!1)}}const on=rn;class an{constructor(e,t){let n,r;n=e||new on,r=t||new on,this._stack=[{scope:n}],this._isolationScope=r}withScope(e){const t=this._pushScope();let n;try{n=e(t)}catch(e){throw this._popScope(),e}return ue(n)?n.then((e=>(this._popScope(),e)),(e=>{throw this._popScope(),e})):(this._popScope(),n)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){const e=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:e}),e}_popScope(){return!(this._stack.length<=1)&&!!this._stack.pop()}}function sn(){const e=Xt(Kt());return e.stack=e.stack||new an(Me(\"defaultCurrentScope\",(()=>new on)),Me(\"defaultIsolationScope\",(()=>new on)))}function cn(e){return sn().withScope(e)}function ln(e,t){const n=sn();return n.withScope((()=>(n.getStackTop().scope=e,t(e))))}function un(e){return sn().withScope((()=>e(sn().getIsolationScope())))}function dn(e){const t=Xt(e);return t.acs?t.acs:{withIsolationScope:un,withScope:cn,withSetScope:ln,withSetIsolationScope:(e,t)=>un(t),getCurrentScope:()=>sn().getScope(),getIsolationScope:()=>sn().getIsolationScope()}}function pn(){return dn(Kt()).getCurrentScope()}function hn(){return dn(Kt()).getIsolationScope()}function fn(){return pn().getClient()}function vn(e){const t=e._sentryMetrics;if(!t)return;const n={};for(const[,[e,r]]of t){(n[e]||(n[e]=[])).push(ze(r))}return n}function gn(e){const{spanId:t,traceId:n}=e.spanContext(),{parent_span_id:r}=_n(e);return ze({parent_span_id:r,span_id:t,trace_id:n})}function mn(e){return\"number\"==typeof e?yn(e):Array.isArray(e)?e[0]+e[1]/1e9:e instanceof Date?yn(e.getTime()):ut()}function yn(e){return e>9999999999?e/1e3:e}function _n(e){if(function(e){return\"function\"==typeof e.getSpanJSON}(e))return e.getSpanJSON();try{const{spanId:t,traceId:n}=e.spanContext();if(function(e){const t=e;return!!(t.attributes&&t.startTime&&t.name&&t.endTime&&t.status)}(e)){const{attributes:r,startTime:i,name:o,endTime:a,parentSpanId:s,status:c}=e;return ze({span_id:t,trace_id:n,data:r,description:o,parent_span_id:s,start_timestamp:mn(i),timestamp:mn(a)||void 0,status:bn(c),op:r[\"sentry.op\"],origin:r[\"sentry.origin\"],_metrics_summary:vn(e)})}return{span_id:t,trace_id:n}}catch(e){return{}}}function bn(e){if(e&&0!==e.code)return 1===e.code?\"ok\":e.message||\"unknown_error\"}function wn(e){return e._sentryRootSpan||e}const kn=\"production\";function Sn(e,t){const n=t.getOptions(),{publicKey:r}=t.getDsn()||{},i=ze({environment:n.environment||kn,release:n.release,public_key:r,trace_id:e});return t.emit(\"createDsc\",i),i}function Mn(e){const t=fn();if(!t)return{};const n=Sn(_n(e).trace_id||\"\",t),r=wn(e),i=r._frozenDsc;if(i)return i;const o=r.spanContext().traceState,a=o&&o.get(\"sentry.dsc\"),s=a&&Nt(a);if(s)return s;const c=_n(r),l=c.data||{},u=l[\"sentry.sample_rate\"];null!=u&&(n.sample_rate=`${u}`);const d=l[\"sentry.source\"],p=c.description;return\"url\"!==d&&p&&(n.transaction=p),function(e){if(\"boolean\"==typeof __SENTRY_TRACING__&&!__SENTRY_TRACING__)return!1;const t=fn(),n=e||t&&t.getOptions();return!!n&&(n.enableTracing||\"tracesSampleRate\"in n||\"tracesSampler\"in n)}()&&(n.sampled=String(function(e){const{traceFlags:t}=e.spanContext();return 1===t}(r))),t.emit(\"createDsc\",n,r),n}function Cn(e,t,n,r){const i=Wt(n),o=e.type&&\"replay_event\"!==e.type?e.type:\"event\";!function(e,t){t&&(e.sdk=e.sdk||{},e.sdk.name=e.sdk.name||t.name,e.sdk.version=e.sdk.version||t.version,e.sdk.integrations=[...e.sdk.integrations||[],...t.integrations||[]],e.sdk.packages=[...e.sdk.packages||[],...t.packages||[]])}(e,n&&n.sdk);const a=function(e,t,n,r){const i=e.sdkProcessingMetadata&&e.sdkProcessingMetadata.dynamicSamplingContext;return{event_id:e.event_id,sent_at:(new Date).toISOString(),...t&&{sdk:t},...!!n&&r&&{dsn:Ie(r)},...i&&{trace:ze({...i})}}}(e,i,r,t);delete e.sdkProcessingMetadata;return Rt(a,[[{type:o},e]])}function En(e,t,n,r=0){return new At(((i,o)=>{const a=e[r];if(null===t||\"function\"!=typeof a)i(t);else{const s=a({...t},n);Yt&&a.id&&null===s&&Le.log(`Event processor \"${a.id}\" dropped event`),ue(s)?s.then((t=>En(e,t,n,r+1).then(i))).then(null,o):En(e,s,n,r+1).then(i).then(null,o)}}))}function Tn(e,t){const{fingerprint:n,span:r,breadcrumbs:i,sdkProcessingMetadata:o}=t;!function(e,t){const{extra:n,tags:r,user:i,contexts:o,level:a,transactionName:s}=t,c=ze(n);c&&Object.keys(c).length&&(e.extra={...c,...e.extra});const l=ze(r);l&&Object.keys(l).length&&(e.tags={...l,...e.tags});const u=ze(i);u&&Object.keys(u).length&&(e.user={...u,...e.user});const d=ze(o);d&&Object.keys(d).length&&(e.contexts={...d,...e.contexts});a&&(e.level=a);s&&\"transaction\"!==e.type&&(e.transaction=s)}(e,t),r&&function(e,t){e.contexts={trace:gn(t),...e.contexts},e.sdkProcessingMetadata={dynamicSamplingContext:Mn(t),...e.sdkProcessingMetadata};const n=wn(t),r=_n(n).description;r&&!e.transaction&&\"transaction\"===e.type&&(e.transaction=r)}(e,r),function(e,t){e.fingerprint=e.fingerprint?function(e){return Array.isArray(e)?e:[e]}(e.fingerprint):[],t&&(e.fingerprint=e.fingerprint.concat(t));e.fingerprint&&!e.fingerprint.length&&delete e.fingerprint}(e,n),function(e,t){const n=[...e.breadcrumbs||[],...t];e.breadcrumbs=n.length?n:void 0}(e,i),function(e,t){e.sdkProcessingMetadata={...e.sdkProcessingMetadata,...t}}(e,o)}function Pn(e,t){const{extra:n,tags:r,user:i,contexts:o,level:a,sdkProcessingMetadata:s,breadcrumbs:c,fingerprint:l,eventProcessors:u,attachments:d,propagationContext:p,transactionName:h,span:f}=t;On(e,\"extra\",n),On(e,\"tags\",r),On(e,\"user\",i),On(e,\"contexts\",o),On(e,\"sdkProcessingMetadata\",s),a&&(e.level=a),h&&(e.transactionName=h),f&&(e.span=f),c.length&&(e.breadcrumbs=[...e.breadcrumbs,...c]),l.length&&(e.fingerprint=[...e.fingerprint,...l]),u.length&&(e.eventProcessors=[...e.eventProcessors,...u]),d.length&&(e.attachments=[...e.attachments,...d]),e.propagationContext={...e.propagationContext,...p}}function On(e,t,n){if(n&&Object.keys(n).length){e[t]={...e[t]};for(const r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[t][r]=n[r])}}function An(e,t,n,r,i,o){const{normalizeDepth:a=3,normalizeMaxBreadth:s=1e3}=e,c={...t,event_id:t.event_id||n.event_id||yt(),timestamp:t.timestamp||lt()},l=n.integrations||e.integrations.map((e=>e.name));!function(e,t){const{environment:n,release:r,dist:i,maxValueLength:o=250}=t;\"environment\"in e||(e.environment=\"environment\"in t?n:kn);void 0===e.release&&void 0!==r&&(e.release=r);void 0===e.dist&&void 0!==i&&(e.dist=i);e.message&&(e.message=he(e.message,o));const a=e.exception&&e.exception.values&&e.exception.values[0];a&&a.value&&(a.value=he(a.value,o));const s=e.request;s&&s.url&&(s.url=he(s.url,o))}(c,e),function(e,t){t.length>0&&(e.sdk=e.sdk||{},e.sdk.integrations=[...e.sdk.integrations||[],...t])}(c,l),i&&i.emit(\"applyFrameMetadata\",t),void 0===t.type&&function(e,t){const n=Se._sentryDebugIds;if(!n)return;let r;const i=jn.get(t);i?r=i:(r=new Map,jn.set(t,r));const o=Object.entries(n).reduce(((e,[n,i])=>{let o;const a=r.get(n);a?o=a:(o=t(n),r.set(n,o));for(let t=o.length-1;t>=0;t--){const n=o[t];if(n.filename){e[n.filename]=i;break}}return e}),{});try{e.exception.values.forEach((e=>{e.stacktrace.frames.forEach((e=>{e.filename&&(e.debug_id=o[e.filename])}))}))}catch(e){}}(c,e.stackParser);const u=function(e,t){if(!t)return e;const n=e?e.clone():new on;return n.update(t),n}(r,n.captureContext);n.mechanism&&kt(c,n.mechanism);const d=i?i.getEventProcessors():[],p=Me(\"globalScope\",(()=>new on)).getScopeData();if(o){Pn(p,o.getScopeData())}if(u){Pn(p,u.getScopeData())}const h=[...n.attachments||[],...p.attachments];h.length&&(n.attachments=h),Tn(c,p);return En([...d,...p.eventProcessors],c,n).then((e=>(e&&function(e){const t={};try{e.exception.values.forEach((e=>{e.stacktrace.frames.forEach((e=>{e.debug_id&&(e.abs_path?t[e.abs_path]=e.debug_id:e.filename&&(t[e.filename]=e.debug_id),delete e.debug_id)}))}))}catch(e){}if(0===Object.keys(t).length)return;e.debug_meta=e.debug_meta||{},e.debug_meta.images=e.debug_meta.images||[];const n=e.debug_meta.images;Object.entries(t).forEach((([e,t])=>{n.push({type:\"sourcemap\",code_file:e,debug_id:t})}))}(e),\"number\"==typeof a&&a>0?function(e,t,n){if(!e)return null;const r={...e,...e.breadcrumbs&&{breadcrumbs:e.breadcrumbs.map((e=>({...e,...e.data&&{data:Mt(e.data,t,n)}})))},...e.user&&{user:Mt(e.user,t,n)},...e.contexts&&{contexts:Mt(e.contexts,t,n)},...e.extra&&{extra:Mt(e.extra,t,n)}};e.contexts&&e.contexts.trace&&r.contexts&&(r.contexts.trace=e.contexts.trace,e.contexts.trace.data&&(r.contexts.trace.data=Mt(e.contexts.trace.data,t,n)));e.spans&&(r.spans=e.spans.map((e=>({...e,...e.data&&{data:Mt(e.data,t,n)}}))));return r}(e,a,s):e)))}const jn=new WeakMap;function Ln(e){if(e)return function(e){return e instanceof on||\"function\"==typeof e}(e)||function(e){return Object.keys(e).some((e=>xn.includes(e)))}(e)?{captureContext:e}:e}const xn=[\"user\",\"level\",\"extra\",\"contexts\",\"tags\",\"fingerprint\",\"requestSession\",\"propagationContext\"];function In(e,t){return pn().captureEvent(e,t)}function Dn(e,t){return n={sentry_key:e.publicKey,sentry_version:\"7\",...t&&{sentry_client:`${t.name}/${t.version}`}},Object.keys(n).map((e=>`${encodeURIComponent(e)}=${encodeURIComponent(n[e])}`)).join(\"&\");var n}const Nn=[];function Fn(e,t){for(const n of t)n&&n.afterAllSetup&&n.afterAllSetup(e)}function Rn(e,t,n){if(n[t.name])Yt&&Le.log(`Integration skipped because it was already installed: ${t.name}`);else{if(n[t.name]=t,-1===Nn.indexOf(t.name)&&\"function\"==typeof t.setupOnce&&(t.setupOnce(),Nn.push(t.name)),t.setup&&\"function\"==typeof t.setup&&t.setup(e),\"function\"==typeof t.preprocessEvent){const n=t.preprocessEvent.bind(t);e.on(\"preprocessEvent\",((t,r)=>n(t,r,e)))}if(\"function\"==typeof t.processEvent){const n=t.processEvent.bind(t),r=Object.assign(((t,r)=>n(t,r,e)),{id:t.name});e.addEventProcessor(r)}Yt&&Le.log(`Integration installed: ${t.name}`)}}const Bn=\"Not capturing exception because it's already been captured.\";class Un{constructor(e){if(this._options=e,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],e.dsn?this._dsn=Ne(e.dsn):Yt&&Le.warn(\"No DSN provided, client will not send events.\"),this._dsn){const i=(t=this._dsn,n=e.tunnel,r=e._metadata?e._metadata.sdk:void 0,n||`${function(e){return`${function(e){const t=e.protocol?`${e.protocol}:`:\"\",n=e.port?`:${e.port}`:\"\";return`${t}//${e.host}${n}${e.path?`/${e.path}`:\"\"}/api/`}(e)}${e.projectId}/envelope/`}(t)}?${Dn(t,r)}`);this._transport=e.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...e.transportOptions,url:i})}var t,n,r}captureException(e,t,n){const r=yt();if(St(e))return Yt&&Le.log(Bn),r;const i={event_id:r,...t};return this._process(this.eventFromException(e,i).then((e=>this._captureEvent(e,i,n)))),i.event_id}captureMessage(e,t,n,r){const i={event_id:yt(),...n},o=ae(e)?e:String(e),a=se(e)?this.eventFromMessage(o,t,i):this.eventFromException(e,i);return this._process(a.then((e=>this._captureEvent(e,i,r)))),i.event_id}captureEvent(e,t,n){const r=yt();if(t&&t.originalException&&St(t.originalException))return Yt&&Le.log(Bn),r;const i={event_id:r,...t},o=(e.sdkProcessingMetadata||{}).capturedSpanScope;return this._process(this._captureEvent(e,i,o||n)),i.event_id}captureSession(e){\"string\"!=typeof e.release?Yt&&Le.warn(\"Discarded session because of missing or non-string release\"):(this.sendSession(e),Zt(e,{init:!1}))}getDsn(){return this._dsn}getOptions(){return this._options}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}flush(e){const t=this._transport;return t?(this.emit(\"flush\"),this._isClientDoneProcessing(e).then((n=>t.flush(e).then((e=>n&&e))))):Pt(!0)}close(e){return this.flush(e).then((e=>(this.getOptions().enabled=!1,this.emit(\"close\"),e)))}getEventProcessors(){return this._eventProcessors}addEventProcessor(e){this._eventProcessors.push(e)}init(){(this._isEnabled()||this._options.integrations.some((({name:e})=>e.startsWith(\"Spotlight\"))))&&this._setupIntegrations()}getIntegrationByName(e){return this._integrations[e]}addIntegration(e){const t=this._integrations[e.name];Rn(this,e,this._integrations),t||Fn(this,[e])}sendEvent(e,t={}){this.emit(\"beforeSendEvent\",e,t);let n=Cn(e,this._dsn,this._options._metadata,this._options.tunnel);for(const e of t.attachments||[])n=Bt(n,$t(e));const r=this.sendEnvelope(n);r&&r.then((t=>this.emit(\"afterSendEvent\",e,t)),null)}sendSession(e){const t=function(e,t,n,r){const i=Wt(n);return Rt({sent_at:(new Date).toISOString(),...i&&{sdk:i},...!!r&&t&&{dsn:Ie(t)}},[\"aggregates\"in e?[{type:\"sessions\"},e]:[{type:\"session\"},e.toJSON()]])}(e,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(t)}recordDroppedEvent(e,t,n){if(this._options.sendClientReports){const r=\"number\"==typeof n?n:1,i=`${e}:${t}`;Yt&&Le.log(`Recording outcome: \"${i}\"${r>1?` (${r} times)`:\"\"}`),this._outcomes[i]=(this._outcomes[i]||0)+r}}on(e,t){const n=this._hooks[e]=this._hooks[e]||[];return n.push(t),()=>{const e=n.indexOf(t);e>-1&&n.splice(e,1)}}emit(e,...t){const n=this._hooks[e];n&&n.forEach((e=>e(...t)))}sendEnvelope(e){return this.emit(\"beforeEnvelope\",e),this._isEnabled()&&this._transport?this._transport.send(e).then(null,(e=>(Yt&&Le.error(\"Error while sending event:\",e),e))):(Yt&&Le.error(\"Transport disabled\"),Pt({}))}_setupIntegrations(){const{integrations:e}=this._options;this._integrations=function(e,t){const n={};return t.forEach((t=>{t&&Rn(e,t,n)})),n}(this,e),Fn(this,e)}_updateSessionFromEvent(e,t){let n=!1,r=!1;const i=t.exception&&t.exception.values;if(i){r=!0;for(const e of i){const t=e.mechanism;if(t&&!1===t.handled){n=!0;break}}}const o=\"ok\"===e.status;(o&&0===e.errors||o&&n)&&(Zt(e,{...n&&{status:\"crashed\"},errors:e.errors||Number(r||n)}),this.captureSession(e))}_isClientDoneProcessing(e){return new At((t=>{let n=0;const r=setInterval((()=>{0==this._numProcessing?(clearInterval(r),t(!0)):(n+=1,e&&n>=e&&(clearInterval(r),t(!1)))}),1)}))}_isEnabled(){return!1!==this.getOptions().enabled&&void 0!==this._transport}_prepareEvent(e,t,n,r=hn()){const i=this.getOptions(),o=Object.keys(this._integrations);return!t.integrations&&o.length>0&&(t.integrations=o),this.emit(\"preprocessEvent\",e,t),e.type||r.setLastEventId(e.event_id||t.event_id),An(i,e,t,n,this,r).then((e=>{if(null===e)return e;const t={...r.getPropagationContext(),...n?n.getPropagationContext():void 0};if(!(e.contexts&&e.contexts.trace)&&t){const{traceId:n,spanId:r,parentSpanId:i,dsc:o}=t;e.contexts={trace:ze({trace_id:n,span_id:r,parent_span_id:i}),...e.contexts};const a=o||Sn(n,this);e.sdkProcessingMetadata={dynamicSamplingContext:a,...e.sdkProcessingMetadata}}return e}))}_captureEvent(e,t={},n){return this._processEvent(e,t,n).then((e=>e.event_id),(e=>{if(Yt){const t=e;\"log\"===t.logLevel?Le.log(t.message):Le.warn(t)}}))}_processEvent(e,t,n){const r=this.getOptions(),{sampleRate:i}=r,o=Jn(e),a=Vn(e),s=e.type||\"error\",c=`before send for type \\`${s}\\``,l=void 0===i?void 0:function(e){if(\"boolean\"==typeof e)return Number(e);const t=\"string\"==typeof e?parseFloat(e):e;if(!(\"number\"!=typeof t||isNaN(t)||t<0||t>1))return t;Yt&&Le.warn(`[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(e)} of type ${JSON.stringify(typeof e)}.`)}(i);if(a&&\"number\"==typeof l&&Math.random()>l)return this.recordDroppedEvent(\"sample_rate\",\"error\",e),Ot(new Fe(`Discarding event because it's not included in the random sample (sampling rate = ${i})`,\"log\"));const u=\"replay_event\"===s?\"replay\":s,d=(e.sdkProcessingMetadata||{}).capturedSpanIsolationScope;return this._prepareEvent(e,t,n,d).then((n=>{if(null===n)throw this.recordDroppedEvent(\"event_processor\",u,e),new Fe(\"An event processor returned `null`, will not send event.\",\"log\");if(t.data&&!0===t.data.__sentry__)return n;const i=function(e,t,n,r){const{beforeSend:i,beforeSendTransaction:o,beforeSendSpan:a}=t;if(Vn(n)&&i)return i(n,r);if(Jn(n)){if(n.spans&&a){const t=[];for(const r of n.spans){const n=a(r);n?t.push(n):e.recordDroppedEvent(\"before_send\",\"span\")}n.spans=t}if(o){if(n.spans){const e=n.spans.length;n.sdkProcessingMetadata={...n.sdkProcessingMetadata,spanCountBeforeProcessing:e}}return o(n,r)}}return n}(this,r,n,t);return function(e,t){const n=`${t} must return \\`null\\` or a valid event.`;if(ue(e))return e.then((e=>{if(!ce(e)&&null!==e)throw new Fe(n);return e}),(e=>{throw new Fe(`${t} rejected with ${e}`)}));if(!ce(e)&&null!==e)throw new Fe(n);return e}(i,c)})).then((r=>{if(null===r){if(this.recordDroppedEvent(\"before_send\",u,e),o){const t=1+(e.spans||[]).length;this.recordDroppedEvent(\"before_send\",\"span\",t)}throw new Fe(`${c} returned \\`null\\`, will not send event.`,\"log\")}const i=n&&n.getSession();if(!o&&i&&this._updateSessionFromEvent(i,r),o){const e=(r.sdkProcessingMetadata&&r.sdkProcessingMetadata.spanCountBeforeProcessing||0)-(r.spans?r.spans.length:0);e>0&&this.recordDroppedEvent(\"before_send\",\"span\",e)}const a=r.transaction_info;if(o&&a&&r.transaction!==e.transaction){const e=\"custom\";r.transaction_info={...a,source:e}}return this.sendEvent(r,t),r})).then(null,(e=>{if(e instanceof Fe)throw e;throw this.captureException(e,{data:{__sentry__:!0},originalException:e}),new Fe(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${e}`)}))}_process(e){this._numProcessing++,e.then((e=>(this._numProcessing--,e)),(e=>(this._numProcessing--,e)))}_clearOutcomes(){const e=this._outcomes;return this._outcomes={},Object.entries(e).map((([e,t])=>{const[n,r]=e.split(\":\");return{reason:n,category:r,quantity:t}}))}_flushOutcomes(){Yt&&Le.log(\"Flushing outcomes...\");const e=this._clearOutcomes();if(0===e.length)return void(Yt&&Le.log(\"No outcomes to send\"));if(!this._dsn)return void(Yt&&Le.log(\"No dsn provided, will not send outcomes\"));Yt&&Le.log(\"Sending outcomes:\",e);const t=(n=e,Rt((r=this._options.tunnel&&Ie(this._dsn))?{dsn:r}:{},[[{type:\"client_report\"},{timestamp:i||lt(),discarded_events:n}]]));var n,r,i;this.sendEnvelope(t)}}function Vn(e){return void 0===e.type}function Jn(e){return\"transaction\"===e.type}function $n(e,t,n=jt(e.bufferSize||64)){let r={};return{send:function(i){const o=[];if(Ut(i,((t,n)=>{const i=zt(n);if(function(e,t,n=Date.now()){return function(e,t){return e[t]||e.all||0}(e,t)>n}(r,i)){const r=qn(t,n);e.recordDroppedEvent(\"ratelimit_backoff\",i,r)}else o.push(t)})),0===o.length)return Pt({});const a=Rt(i[0],o),s=t=>{Ut(a,((n,r)=>{const i=qn(n,r);e.recordDroppedEvent(t,zt(r),i)}))};return n.add((()=>t({body:Jt(a)}).then((e=>(void 0!==e.statusCode&&(e.statusCode<200||e.statusCode>=300)&&Yt&&Le.warn(`Sentry responded with status code ${e.statusCode} to sent event.`),r=Ht(r,e),e)),(e=>{throw s(\"network_error\"),e})))).then((e=>e),(e=>{if(e instanceof Fe)return Yt&&Le.error(\"Skipped sending event because buffer is full.\"),s(\"queue_overflow\"),Pt({});throw e}))},flush:e=>n.drain(e)}}function qn(e,t){if(\"event\"===t||\"transaction\"===t)return Array.isArray(e)?e[1]:void 0}const zn=100;function Wn(e,t){const n=fn(),r=hn();if(!n)return;const{beforeBreadcrumb:i=null,maxBreadcrumbs:o=zn}=n.getOptions();if(o<=0)return;const a={timestamp:lt(),...e},s=i?je((()=>i(a,t))):a;null!==s&&(n.emit&&n.emit(\"beforeAddBreadcrumb\",s,t),r.addBreadcrumb(s,o))}let Hn;const Gn=new WeakMap,Qn=()=>({name:\"FunctionToString\",setupOnce(){Hn=Function.prototype.toString;try{Function.prototype.toString=function(...e){const t=Ve(this),n=Gn.has(fn())&&void 0!==t?t:this;return Hn.apply(n,e)}}catch(e){}},setup(e){Gn.set(e,!0)}}),Yn=[/^Script error\\.?$/,/^Javascript error: Script error\\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/,\"undefined is not an object (evaluating 'a.L')\",'can\\'t redefine non-configurable property \"solana\"',\"vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)\",\"Can't find variable: _AutofillCallbackHandler\"],Kn=(e={})=>({name:\"InboundFilters\",processEvent(t,n,r){const i=r.getOptions(),o=function(e={},t={}){return{allowUrls:[...e.allowUrls||[],...t.allowUrls||[]],denyUrls:[...e.denyUrls||[],...t.denyUrls||[]],ignoreErrors:[...e.ignoreErrors||[],...t.ignoreErrors||[],...e.disableErrorDefaults?[]:Yn],ignoreTransactions:[...e.ignoreTransactions||[],...t.ignoreTransactions||[]],ignoreInternal:void 0===e.ignoreInternal||e.ignoreInternal}}(e,i);return function(e,t){if(t.ignoreInternal&&function(e){try{return\"SentryError\"===e.exception.values[0].type}catch(e){}return!1}(e))return Yt&&Le.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${bt(e)}`),!0;if(function(e,t){if(e.type||!t||!t.length)return!1;return function(e){const t=[];e.message&&t.push(e.message);let n;try{n=e.exception.values[e.exception.values.length-1]}catch(e){}n&&n.value&&(t.push(n.value),n.type&&t.push(`${n.type}: ${n.value}`));return t}(e).some((e=>ge(e,t)))}(e,t.ignoreErrors))return Yt&&Le.warn(`Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${bt(e)}`),!0;if(function(e){if(e.type)return!1;if(!e.exception||!e.exception.values||0===e.exception.values.length)return!1;return!e.message&&!e.exception.values.some((e=>e.stacktrace||e.type&&\"Error\"!==e.type||e.value))}(e))return Yt&&Le.warn(`Event dropped due to not having an error message, error type or stacktrace.\\nEvent: ${bt(e)}`),!0;if(function(e,t){if(\"transaction\"!==e.type||!t||!t.length)return!1;const n=e.transaction;return!!n&&ge(n,t)}(e,t.ignoreTransactions))return Yt&&Le.warn(`Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${bt(e)}`),!0;if(function(e,t){if(!t||!t.length)return!1;const n=Xn(e);return!!n&&ge(n,t)}(e,t.denyUrls))return Yt&&Le.warn(`Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${bt(e)}.\\nUrl: ${Xn(e)}`),!0;if(!function(e,t){if(!t||!t.length)return!0;const n=Xn(e);return!n||ge(n,t)}(e,t.allowUrls))return Yt&&Le.warn(`Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${bt(e)}.\\nUrl: ${Xn(e)}`),!0;return!1}(t,o)?null:t}});function Xn(e){try{let t;try{t=e.exception.values[0].stacktrace.frames}catch(e){}return t?function(e=[]){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n&&\"\"!==n.filename&&\"[native code]\"!==n.filename)return n.filename||null}return null}(t):null}catch(t){return Yt&&Le.error(`Cannot extract url for event ${bt(e)}`),null}}const Zn=()=>{let e;return{name:\"Dedupe\",processEvent(t){if(t.type)return t;try{if(function(e,t){if(!t)return!1;if(function(e,t){const n=e.message,r=t.message;if(!n&&!r)return!1;if(n&&!r||!n&&r)return!1;if(n!==r)return!1;if(!tr(e,t))return!1;if(!er(e,t))return!1;return!0}(e,t))return!0;if(function(e,t){const n=nr(t),r=nr(e);if(!n||!r)return!1;if(n.type!==r.type||n.value!==r.value)return!1;if(!tr(e,t))return!1;if(!er(e,t))return!1;return!0}(e,t))return!0;return!1}(t,e))return Yt&&Le.warn(\"Event dropped due to being a duplicate of previously captured event.\"),null}catch(e){}return e=t}}};function er(e,t){let n=Ze(e),r=Ze(t);if(!n&&!r)return!0;if(n&&!r||!n&&r)return!1;if(r.length!==n.length)return!1;for(let e=0;e0}function ar(e,t={},n){if(\"function\"!=typeof e)return e;try{const t=e.__sentry_wrapped__;if(t)return\"function\"==typeof t?t:e;if(Ve(e))return e}catch(t){return e}const r=function(){const r=Array.prototype.slice.call(arguments);try{n&&\"function\"==typeof n&&n.apply(this,arguments);const i=r.map((e=>ar(e,t)));return e.apply(this,i)}catch(e){throw ir++,setTimeout((()=>{ir--})),function(...e){const t=dn(Kt());if(2===e.length){const[n,r]=e;return n?t.withSetScope(n,r):t.withScope(r)}t.withScope(e[0])}((n=>{var i,o;n.addEventProcessor((e=>(t.mechanism&&(wt(e,void 0,void 0),kt(e,t.mechanism)),e.extra={...e.extra,arguments:r},e))),i=e,pn().captureException(i,Ln(o))})),e}};try{for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(r[t]=e[t])}catch(e){}Ue(r,e),Be(e,\"__sentry_wrapped__\",r);try{Object.getOwnPropertyDescriptor(r,\"name\").configurable&&Object.defineProperty(r,\"name\",{get:()=>e.name})}catch(e){}return r}const sr=\"undefined\"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__;function cr(e,t){const n=dr(e,t),r={type:t&&t.name,value:hr(t)};return n.length&&(r.stacktrace={frames:n}),void 0===r.type&&\"\"===r.value&&(r.value=\"Unrecoverable error caught\"),r}function lr(e,t,n,r){const i=fn(),o=i&&i.getOptions().normalizeDepth,a=function(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const n=e[t];if(n instanceof Error)return n}return}(t),s={__serialized__:Ct(t,o)};if(a)return{exception:{values:[cr(e,a)]},extra:s};const c={exception:{values:[{type:le(t)?t.constructor.name:r?\"UnhandledRejection\":\"Error\",value:gr(t,{isUnhandledRejection:r})}]},extra:s};if(n){const t=dr(e,n);t.length&&(c.exception.values[0].stacktrace={frames:t})}return c}function ur(e,t){return{exception:{values:[cr(e,t)]}}}function dr(e,t){const n=t.stacktrace||t.stack||\"\",r=function(e){if(e&&pr.test(e.message))return 1;return 0}(t),i=function(e){if(\"number\"==typeof e.framesToPop)return e.framesToPop;return 0}(t);try{return e(n,r,i)}catch(e){}return[]}const pr=/Minified React error #\\d+;/i;function hr(e){const t=e&&e.message;return t?t.error&&\"string\"==typeof t.error.message?t.error.message:t:\"No error message\"}function fr(e,t,n,r,i){let o;if(re(t)&&t.error){return ur(e,t.error)}if(ie(t)||ne(t,\"DOMException\")){const i=t;if(\"stack\"in t)o=ur(e,t);else{const t=i.name||(ie(i)?\"DOMError\":\"DOMException\"),a=i.message?`${t}: ${i.message}`:t;o=vr(e,a,n,r),wt(o,a)}return\"code\"in i&&(o.tags={...o.tags,\"DOMException.code\":`${i.code}`}),o}if(te(t))return ur(e,t);if(ce(t)||le(t)){return o=lr(e,t,n,i),kt(o,{synthetic:!0}),o}return o=vr(e,t,n,r),wt(o,`${t}`,void 0),kt(o,{synthetic:!0}),o}function vr(e,t,n,r){const i={};if(r&&n){const r=dr(e,n);r.length&&(i.exception={values:[{value:t,stacktrace:{frames:r}}]})}if(ae(t)){const{__sentry_template_string__:e,__sentry_template_values__:n}=t;return i.logentry={message:e,params:n},i}return i.message=t,i}function gr(e,{isUnhandledRejection:t}){const n=function(e,t=40){const n=Object.keys(Je(e));n.sort();const r=n[0];if(!r)return\"[object has no keys]\";if(r.length>=t)return he(r,t);for(let e=n.length;e>0;e--){const r=n.slice(0,e).join(\", \");if(!(r.length>t))return e===n.length?r:he(r,t)}return\"\"}(e),r=t?\"promise rejection\":\"exception\";if(re(e))return`Event \\`ErrorEvent\\` captured as ${r} with message \\`${e.message}\\``;if(le(e)){return`Event \\`${function(e){try{const t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){}}(e)}\\` (type=${e.type}) captured as ${r}`}return`Object captured as ${r} with keys: ${n}`}class mr extends Un{constructor(e){const t={parentSpanIsAlwaysRootSpan:!0,...e};!function(e,t,n=[t],r=\"npm\"){const i=e._metadata||{};i.sdk||(i.sdk={name:`sentry.javascript.${t}`,packages:n.map((e=>({name:`${r}:@sentry/${e}`,version:ke}))),version:ke}),e._metadata=i}(t,\"browser\",[\"browser\"],rr.SENTRY_SDK_SOURCE||\"npm\"),super(t),t.sendClientReports&&rr.document&&rr.document.addEventListener(\"visibilitychange\",(()=>{\"hidden\"===rr.document.visibilityState&&this._flushOutcomes()}))}eventFromException(e,t){return function(e,t,n,r){const i=fr(e,t,n&&n.syntheticException||void 0,r);return kt(i),i.level=\"error\",n&&n.event_id&&(i.event_id=n.event_id),Pt(i)}(this._options.stackParser,e,t,this._options.attachStacktrace)}eventFromMessage(e,t=\"info\",n){return function(e,t,n=\"info\",r,i){const o=vr(e,t,r&&r.syntheticException||void 0,i);return o.level=n,r&&r.event_id&&(o.event_id=r.event_id),Pt(o)}(this._options.stackParser,e,t,n,this._options.attachStacktrace)}captureUserFeedback(e){if(!this._isEnabled())return void(sr&&Le.warn(\"SDK not enabled, will not capture user feedback.\"));const t=function(e,{metadata:t,tunnel:n,dsn:r}){const i={event_id:e.event_id,sent_at:(new Date).toISOString(),...t&&t.sdk&&{sdk:{name:t.sdk.name,version:t.sdk.version}},...!!n&&!!r&&{dsn:Ie(r)}},o=function(e){return[{type:\"user_report\"},e]}(e);return Rt(i,[o])}(e,{metadata:this.getSdkMetadata(),dsn:this.getDsn(),tunnel:this.getOptions().tunnel});this.sendEnvelope(t)}_prepareEvent(e,t,n){return e.platform=e.platform||\"javascript\",super._prepareEvent(e,t,n)}}const yr=\"undefined\"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,_r=Se;let br,wr,kr,Sr;function Mr(){if(!_r.document)return;const e=it.bind(null,\"dom\"),t=Cr(e,!0);_r.document.addEventListener(\"click\",t,!1),_r.document.addEventListener(\"keypress\",t,!1),[\"EventTarget\",\"Node\"].forEach((t=>{const n=_r[t]&&_r[t].prototype;n&&n.hasOwnProperty&&n.hasOwnProperty(\"addEventListener\")&&(Re(n,\"addEventListener\",(function(t){return function(n,r,i){if(\"click\"===n||\"keypress\"==n)try{const r=this,o=r.__sentry_instrumentation_handlers__=r.__sentry_instrumentation_handlers__||{},a=o[n]=o[n]||{refCount:0};if(!a.handler){const r=Cr(e);a.handler=r,t.call(this,n,r,i)}a.refCount++}catch(e){}return t.call(this,n,r,i)}})),Re(n,\"removeEventListener\",(function(e){return function(t,n,r){if(\"click\"===t||\"keypress\"==t)try{const n=this,i=n.__sentry_instrumentation_handlers__||{},o=i[t];o&&(o.refCount--,o.refCount<=0&&(e.call(this,t,o.handler,r),o.handler=void 0,delete i[t]),0===Object.keys(i).length&&delete n.__sentry_instrumentation_handlers__)}catch(e){}return e.call(this,t,n,r)}})))}))}function Cr(e,t=!1){return n=>{if(!n||n._sentryCaptured)return;const r=function(e){try{return e.target}catch(e){return null}}(n);if(function(e,t){return\"keypress\"===e&&(!t||!t.tagName||\"INPUT\"!==t.tagName&&\"TEXTAREA\"!==t.tagName&&!t.isContentEditable)}(n.type,r))return;Be(n,\"_sentryCaptured\",!0),r&&!r._sentryId&&Be(r,\"_sentryId\",yt());const i=\"keypress\"===n.type?\"input\":n.type;if(!function(e){if(e.type!==wr)return!1;try{if(!e.target||e.target._sentryId!==kr)return!1}catch(e){}return!0}(n)){e({event:n,name:i,global:t}),wr=n.type,kr=r?r._sentryId:void 0}clearTimeout(br),br=_r.setTimeout((()=>{kr=void 0,wr=void 0}),1e3)}}function Er(){if(!function(){const e=Qt.chrome,t=e&&e.app&&e.app.runtime,n=\"history\"in Qt&&!!Qt.history.pushState&&!!Qt.history.replaceState;return!t&&n}())return;const e=_r.onpopstate;function t(e){return function(...t){const n=t.length>2?t[2]:void 0;if(n){const e=Sr,t=String(n);Sr=t;it(\"history\",{from:e,to:t})}return e.apply(this,t)}}_r.onpopstate=function(...t){const n=_r.location.href,r=Sr;Sr=n;if(it(\"history\",{from:r,to:n}),e)try{return e.apply(this,t)}catch(e){}},Re(_r.history,\"pushState\",t),Re(_r.history,\"replaceState\",t)}const Tr={};function Pr(e){Tr[e]=void 0}const Or=\"__sentry_xhr_v3__\";function Ar(){if(!_r.XMLHttpRequest)return;const e=XMLHttpRequest.prototype;e.open=new Proxy(e.open,{apply(e,t,n){const r=1e3*ut(),i=oe(n[0])?n[0].toUpperCase():void 0,o=function(e){if(oe(e))return e;try{return e.toString()}catch(e){}return}(n[1]);if(!i||!o)return e.apply(t,n);t[Or]={method:i,url:o,request_headers:{}},\"POST\"===i&&o.match(/sentry_key/)&&(t.__sentry_own_request__=!0);const a=()=>{const e=t[Or];if(e&&4===t.readyState){try{e.status_code=t.status}catch(e){}it(\"xhr\",{endTimestamp:1e3*ut(),startTimestamp:r,xhr:t})}};return\"onreadystatechange\"in t&&\"function\"==typeof t.onreadystatechange?t.onreadystatechange=new Proxy(t.onreadystatechange,{apply:(e,t,n)=>(a(),e.apply(t,n))}):t.addEventListener(\"readystatechange\",a),t.setRequestHeader=new Proxy(t.setRequestHeader,{apply(e,t,n){const[r,i]=n,o=t[Or];return o&&oe(r)&&oe(i)&&(o.request_headers[r.toLowerCase()]=i),e.apply(t,n)}}),e.apply(t,n)}}),e.send=new Proxy(e.send,{apply(e,t,n){const r=t[Or];if(!r)return e.apply(t,n);void 0!==n[0]&&(r.body=n[0]);return it(\"xhr\",{startTimestamp:1e3*ut(),xhr:t}),e.apply(t,n)}})}function jr(e,t=function(e){const t=Tr[e];if(t)return t;let n=_r[e];if(st(n))return Tr[e]=n.bind(_r);const r=_r.document;if(r&&\"function\"==typeof r.createElement)try{const t=r.createElement(\"iframe\");t.hidden=!0,r.head.appendChild(t);const i=t.contentWindow;i&&i[e]&&(n=i[e]),r.head.removeChild(t)}catch(t){yr&&Le.warn(`Could not create sandbox iframe for ${e} check, bailing to window.${e}: `,t)}return n?Tr[e]=n.bind(_r):n}(\"fetch\")){let n=0,r=0;return $n(e,(function(i){const o=i.body.length;n+=o,r++;const a={body:i.body,method:\"POST\",referrerPolicy:\"origin\",headers:e.headers,keepalive:n<=6e4&&r<15,...e.fetchOptions};if(!t)return Pr(\"fetch\"),Ot(\"No fetch implementation available\");try{return t(e.url,a).then((e=>(n-=o,r--,{statusCode:e.status,headers:{\"x-sentry-rate-limits\":e.headers.get(\"X-Sentry-Rate-Limits\"),\"retry-after\":e.headers.get(\"Retry-After\")}})))}catch(e){return Pr(\"fetch\"),n-=o,r--,Ot(e)}}))}function Lr(e,t,n,r){const i={filename:e,function:\"\"===t?He:t,in_app:!0};return void 0!==n&&(i.lineno=n),void 0!==r&&(i.colno=r),i}const xr=/^\\s*at (\\S+?)(?::(\\d+))(?::(\\d+))\\s*$/i,Ir=/^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i,Dr=/\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/,Nr=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i,Fr=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i,Rr=function(...e){const t=e.sort(((e,t)=>e[0]-t[0])).map((e=>e[1]));return(e,n=0,r=0)=>{const i=[],o=e.split(\"\\n\");for(let e=n;e1024)continue;const a=Ge.test(n)?n.replace(Ge,\"$1\"):n;if(!a.match(/\\S*Error: /)){for(const e of t){const t=e(a);if(t){i.push(t);break}}if(i.length>=50+r)break}}return function(e){if(!e.length)return[];const t=Array.from(e);/sentryWrapped/.test(Ye(t).function||\"\")&&t.pop();t.reverse(),Qe.test(Ye(t).function||\"\")&&(t.pop(),Qe.test(Ye(t).function||\"\")&&t.pop());return t.slice(0,50).map((e=>({...e,filename:e.filename||Ye(t).filename,function:e.function||He})))}(i.slice(r))}}(...[[30,e=>{const t=xr.exec(e);if(t){const[,e,n,r]=t;return Lr(e,He,+n,+r)}const n=Ir.exec(e);if(n){if(n[2]&&0===n[2].indexOf(\"eval\")){const e=Dr.exec(n[2]);e&&(n[2]=e[1],n[3]=e[2],n[4]=e[3])}const[e,t]=Br(n[1]||He,n[2]);return Lr(t,e,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}}],[50,e=>{const t=Nr.exec(e);if(t){if(t[3]&&t[3].indexOf(\" > eval\")>-1){const e=Fr.exec(t[3]);e&&(t[1]=t[1]||\"eval\",t[3]=e[1],t[4]=e[2],t[5]=\"\")}let e=t[3],n=t[1]||He;return[n,e]=Br(n,e),Lr(e,n,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}}]]),Br=(e,t)=>{const n=-1!==e.indexOf(\"safari-extension\"),r=-1!==e.indexOf(\"safari-web-extension\");return n||r?[-1!==e.indexOf(\"@\")?e.split(\"@\")[0]:He,n?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},Ur=1024,Vr=(e={})=>{const t={console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0,...e};return{name:\"Breadcrumbs\",setup(e){var n;t.console&&function(e){const t=\"console\";nt(t,e),rt(t,ot)}(function(e){return function(t){if(fn()!==e)return;const n={category:\"console\",data:{arguments:t.args,logger:\"console\"},level:It(t.level),message:fe(t.args,\" \")};if(\"assert\"===t.level){if(!1!==t.args[0])return;n.message=`Assertion failed: ${fe(t.args.slice(1),\" \")||\"console.assert\"}`,n.data.arguments=t.args.slice(1)}Wn(n,{input:t.args,level:t.level})}}(e)),t.dom&&(n=function(e,t){return function(n){if(fn()!==e)return;let r,i,o=\"object\"==typeof t?t.serializeAttribute:void 0,a=\"object\"==typeof t&&\"number\"==typeof t.maxStringLength?t.maxStringLength:void 0;a&&a>Ur&&(sr&&Le.warn(`\\`dom.maxStringLength\\` cannot exceed 1024, but a value of ${a} was configured. Sentry will use 1024 instead.`),a=Ur),\"string\"==typeof o&&(o=[o]);try{const e=n.event,t=function(e){return!!e&&!!e.target}(e)?e.target:e;r=Ee(t,{keyAttrs:o,maxStringLength:a}),i=function(e){if(!Ce.HTMLElement)return null;let t=e;for(let e=0;e<5;e++){if(!t)return null;if(t instanceof HTMLElement){if(t.dataset.sentryComponent)return t.dataset.sentryComponent;if(t.dataset.sentryElement)return t.dataset.sentryElement}t=t.parentNode}return null}(t)}catch(e){r=\"\"}if(0===r.length)return;const s={category:`ui.${n.name}`,message:r};i&&(s.data={\"ui.component_name\":i}),Wn(s,{event:n.event,name:n.name,global:n.global})}}(e,t.dom),nt(\"dom\",n),rt(\"dom\",Mr)),t.xhr&&function(e){nt(\"xhr\",e),rt(\"xhr\",Ar)}(function(e){return function(t){if(fn()!==e)return;const{startTimestamp:n,endTimestamp:r}=t,i=t.xhr[Or];if(!n||!r||!i)return;const{method:o,url:a,status_code:s,body:c}=i,l={method:o,url:a,status_code:s},u={xhr:t.xhr,input:c,startTimestamp:n,endTimestamp:r};Wn({category:\"xhr\",data:l,type:\"http\",level:we(s)},u)}}(e)),t.fetch&&dt(function(e){return function(t){if(fn()!==e)return;const{startTimestamp:n,endTimestamp:r}=t;if(r&&(!t.fetchData.url.match(/sentry_key/)||\"POST\"!==t.fetchData.method))if(t.error){Wn({category:\"fetch\",data:t.fetchData,level:\"error\",type:\"http\"},{data:t.error,input:t.args,startTimestamp:n,endTimestamp:r})}else{const e=t.response,i={...t.fetchData,status_code:e&&e.status},o={input:t.args,response:e,startTimestamp:n,endTimestamp:r};Wn({category:\"fetch\",data:i,type:\"http\",level:we(i.status_code)},o)}}}(e)),t.history&&function(e){const t=\"history\";nt(t,e),rt(t,Er)}(function(e){return function(t){if(fn()!==e)return;let n=t.from,r=t.to;const i=Lt(rr.location.href);let o=n?Lt(n):void 0;const a=Lt(r);o&&o.path||(o=i),i.protocol===a.protocol&&i.host===a.host&&(r=a.relative),i.protocol===o.protocol&&i.host===o.host&&(n=o.relative),Wn({category:\"navigation\",data:{from:n,to:r}})}}(e)),t.sentry&&e.on(\"beforeSendEvent\",function(e){return function(t){fn()===e&&Wn({category:\"sentry.\"+(\"transaction\"===t.type?\"transaction\":\"event\"),event_id:t.event_id,level:t.level,message:bt(t)},{event:t})}}(e))}}};const Jr=[\"EventTarget\",\"Window\",\"Node\",\"ApplicationCache\",\"AudioTrackList\",\"BroadcastChannel\",\"ChannelMergerNode\",\"CryptoOperation\",\"EventSource\",\"FileReader\",\"HTMLUnknownElement\",\"IDBDatabase\",\"IDBRequest\",\"IDBTransaction\",\"KeyOperation\",\"MediaController\",\"MessagePort\",\"ModalWindow\",\"Notification\",\"SVGElementInstance\",\"Screen\",\"SharedWorker\",\"TextTrack\",\"TextTrackCue\",\"TextTrackList\",\"WebSocket\",\"WebSocketWorker\",\"Worker\",\"XMLHttpRequest\",\"XMLHttpRequestEventTarget\",\"XMLHttpRequestUpload\"],$r=(e={})=>{const t={XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0,...e};return{name:\"BrowserApiErrors\",setupOnce(){t.setTimeout&&Re(rr,\"setTimeout\",qr),t.setInterval&&Re(rr,\"setInterval\",qr),t.requestAnimationFrame&&Re(rr,\"requestAnimationFrame\",zr),t.XMLHttpRequest&&\"XMLHttpRequest\"in rr&&Re(XMLHttpRequest.prototype,\"send\",Wr);const e=t.eventTarget;if(e){(Array.isArray(e)?e:Jr).forEach(Hr)}}}};function qr(e){return function(...t){const n=t[0];return t[0]=ar(n,{mechanism:{data:{function:Xe(e)},handled:!1,type:\"instrument\"}}),e.apply(this,t)}}function zr(e){return function(t){return e.apply(this,[ar(t,{mechanism:{data:{function:\"requestAnimationFrame\",handler:Xe(e)},handled:!1,type:\"instrument\"}})])}}function Wr(e){return function(...t){const n=this;return[\"onload\",\"onerror\",\"onprogress\",\"onreadystatechange\"].forEach((e=>{e in n&&\"function\"==typeof n[e]&&Re(n,e,(function(t){const n={mechanism:{data:{function:e,handler:Xe(t)},handled:!1,type:\"instrument\"}},r=Ve(t);return r&&(n.mechanism.data.handler=Xe(r)),ar(t,n)}))})),e.apply(this,t)}}function Hr(e){const t=rr,n=t[e]&&t[e].prototype;n&&n.hasOwnProperty&&n.hasOwnProperty(\"addEventListener\")&&(Re(n,\"addEventListener\",(function(t){return function(n,r,i){try{\"function\"==typeof r.handleEvent&&(r.handleEvent=ar(r.handleEvent,{mechanism:{data:{function:\"handleEvent\",handler:Xe(r),target:e},handled:!1,type:\"instrument\"}}))}catch(e){}return t.apply(this,[n,ar(r,{mechanism:{data:{function:\"addEventListener\",handler:Xe(r),target:e},handled:!1,type:\"instrument\"}}),i])}})),Re(n,\"removeEventListener\",(function(e){return function(t,n,r){const i=n;try{const n=i&&i.__sentry_wrapped__;n&&e.call(this,t,n,r)}catch(e){}return e.call(this,t,i,r)}})))}const Gr=(e={})=>{const t={onerror:!0,onunhandledrejection:!0,...e};return{name:\"GlobalHandlers\",setupOnce(){Error.stackTraceLimit=50},setup(e){t.onerror&&(!function(e){!function(e){const t=\"error\";nt(t,e),rt(t,vt)}((t=>{const{stackParser:n,attachStacktrace:r}=Yr();if(fn()!==e||or())return;const{msg:i,url:o,line:a,column:s,error:c}=t,l=function(e,t,n,r){const i=e.exception=e.exception||{},o=i.values=i.values||[],a=o[0]=o[0]||{},s=a.stacktrace=a.stacktrace||{},c=s.frames=s.frames||[],l=isNaN(parseInt(r,10))?void 0:r,u=isNaN(parseInt(n,10))?void 0:n,d=oe(t)&&t.length>0?t:function(){try{return Ce.document.location.href}catch(e){return\"\"}}();0===c.length&&c.push({colno:l,filename:d,function:He,in_app:!0,lineno:u});return e}(fr(n,c||i,void 0,r,!1),o,a,s);l.level=\"error\",In(l,{originalException:c,mechanism:{handled:!1,type:\"onerror\"}})}))}(e),Qr(\"onerror\")),t.onunhandledrejection&&(!function(e){!function(e){const t=\"unhandledrejection\";nt(t,e),rt(t,mt)}((t=>{const{stackParser:n,attachStacktrace:r}=Yr();if(fn()!==e||or())return;const i=function(e){if(se(e))return e;try{if(\"reason\"in e)return e.reason;if(\"detail\"in e&&\"reason\"in e.detail)return e.detail.reason}catch(e){}return e}(t),o=se(i)?{exception:{values:[{type:\"UnhandledRejection\",value:`Non-Error promise rejection captured with value: ${String(i)}`}]}}:fr(n,i,void 0,r,!0);o.level=\"error\",In(o,{originalException:i,mechanism:{handled:!1,type:\"onunhandledrejection\"}})}))}(e),Qr(\"onunhandledrejection\"))}}};function Qr(e){sr&&Le.log(`Global Handler attached: ${e}`)}function Yr(){const e=fn();return e&&e.getOptions()||{stackParser:()=>[],attachStacktrace:!1}}const Kr=()=>({name:\"HttpContext\",preprocessEvent(e){if(!rr.navigator&&!rr.location&&!rr.document)return;const t=e.request&&e.request.url||rr.location&&rr.location.href,{referrer:n}=rr.document||{},{userAgent:r}=rr.navigator||{},i={...e.request&&e.request.headers,...n&&{Referer:n},...r&&{\"User-Agent\":r}},o={...e.request,...t&&{url:t},headers:i};e.request=o}}),Xr=(e={})=>{const t=e.limit||5,n=e.key||\"cause\";return{name:\"LinkedErrors\",preprocessEvent(e,r,i){const o=i.getOptions();me(cr,o.stackParser,o.maxValueLength,n,t,e,r)}}};var Zr=\"new\",ei=\"loading\",ti=\"loaded\",ni=\"joining-meeting\",ri=\"joined-meeting\",ii=\"left-meeting\",oi=\"error\",ai=\"blocked\",si=\"off\",ci=\"sendable\",li=\"loading\",ui=\"interrupted\",di=\"playable\",pi=\"unknown\",hi=\"full\",fi=\"lobby\",vi=\"none\",gi=\"base\",mi=\"*\",yi=\"ejected\",_i=\"nbf-room\",bi=\"nbf-token\",wi=\"exp-room\",ki=\"exp-token\",Si=\"no-room\",Mi=\"meeting-full\",Ci=\"end-of-life\",Ei=\"not-allowed\",Ti=\"connection-error\",Pi=\"cam-in-use\",Oi=\"mic-in-use\",Ai=\"cam-mic-in-use\",ji=\"permissions\",Li=\"undefined-mediadevices\",xi=\"not-found\",Ii=\"constraints\",Di=\"unknown\",Ni=\"iframe-ready-for-launch-config\",Fi=\"iframe-launch-config\",Ri=\"theme-updated\",Bi=\"loading\",Ui=\"load-attempt-failed\",Vi=\"loaded\",Ji=\"started-camera\",$i=\"camera-error\",qi=\"joining-meeting\",zi=\"joined-meeting\",Wi=\"left-meeting\",Hi=\"participant-joined\",Gi=\"participant-updated\",Qi=\"participant-left\",Yi=\"participant-counts-updated\",Ki=\"access-state-updated\",Xi=\"meeting-session-summary-updated\",Zi=\"meeting-session-state-updated\",eo=\"meeting-session-data-error\",to=\"waiting-participant-added\",no=\"waiting-participant-updated\",ro=\"waiting-participant-removed\",io=\"track-started\",oo=\"track-stopped\",ao=\"transcription-started\",so=\"transcription-stopped\",co=\"transcription-error\",lo=\"recording-started\",uo=\"recording-stopped\",po=\"recording-stats\",ho=\"recording-error\",fo=\"recording-upload-completed\",vo=\"recording-data\",go=\"app-message\",mo=\"transcription-message\",yo=\"remote-media-player-started\",_o=\"remote-media-player-updated\",bo=\"remote-media-player-stopped\",wo=\"local-screen-share-started\",ko=\"local-screen-share-stopped\",So=\"local-screen-share-canceled\",Mo=\"active-speaker-change\",Co=\"active-speaker-mode-change\",Eo=\"network-quality-change\",To=\"network-connection\",Po=\"cpu-load-change\",Oo=\"face-counts-updated\",Ao=\"fullscreen\",jo=\"exited-fullscreen\",Lo=\"live-streaming-started\",xo=\"live-streaming-updated\",Io=\"live-streaming-stopped\",Do=\"live-streaming-error\",No=\"lang-updated\",Fo=\"receive-settings-updated\",Ro=\"input-settings-updated\",Bo=\"nonfatal-error\",Uo=\"error\",Vo=4096,Jo=102400,$o=\"iframe-call-message\",qo=\"local-screen-start\",zo=\"daily-method-update-live-streaming-endpoints\",Wo=\"transmit-log\",Ho=\"daily-custom-track\",Go={NONE:\"none\",BGBLUR:\"background-blur\",BGIMAGE:\"background-image\",FACE_DETECTION:\"face-detection\"},Qo={NONE:\"none\",NOISE_CANCELLATION:\"noise-cancellation\"},Yo={PLAY:\"play\",PAUSE:\"pause\"},Ko=[\"jpg\",\"png\",\"jpeg\"],Xo=\"add-endpoints\",Zo=\"remove-endpoints\",ea=\"sip-call-transfer\";function ta(){return!na()&&\"undefined\"!=typeof window&&window.navigator&&window.navigator.userAgent?window.navigator.userAgent:\"\"}function na(){return\"undefined\"!=typeof navigator&&navigator.product&&\"ReactNative\"===navigator.product}function ra(){return navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function ia(){return!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)&&(function(e,t){if(!e||!t)return!0;switch(e){case\"Chrome\":return t.major>=75;case\"Safari\":return RTCRtpTransceiver.prototype.hasOwnProperty(\"currentDirection\")&&!(13===t.major&&0===t.minor&&0===t.point);case\"Firefox\":return t.major>=67}return!0}(pa(),ha())||na())}function oa(){if(na())return!1;if(!document)return!1;var e=document.createElement(\"iframe\");return!!e.requestFullscreen||!!e.webkitRequestFullscreen}var aa=function(){try{var e=document.createElement(\"canvas\"),t=null!=e.getContext(\"webgl2\");return e.remove(),t}catch(e){return!1}}();function sa(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return!na()&&(!!aa&&(e?function(){if(da())return!1;return[\"Chrome\",\"Firefox\"].includes(pa())}():function(){if(da())return!1;var e=pa();if(\"Safari\"===e){var t=ma();if(t.major<15||15===t.major&&t.minor<4)return!1}if(\"Chrome\"===e){return fa().major>=77}if(\"Firefox\"===e){return ya().major>=97}return[\"Chrome\",\"Firefox\",\"Safari\"].includes(e)}()))}function ca(){if(na())return!1;if(ua())return!1;if(\"undefined\"==typeof AudioWorkletNode)return!1;switch(pa()){case\"Chrome\":case\"Firefox\":return!0;case\"Safari\":var e=ha();return e.major>17||17===e.major&&e.minor>=4}return!1}function la(){return ra()&&!function(){var e,t=pa();if(!ta())return!0;switch(t){case\"Chrome\":return(e=fa()).major&&e.major>0&&e.major<75;case\"Firefox\":return(e=ya()).major<91;case\"Safari\":return(e=ma()).major<13||13===e.major&&e.minor<1;default:return!0}}()}function ua(){return ta().match(/Linux; Android/)}function da(){var e,t,n=ta(),r=n.match(/Mac/)&&(!na()&&\"undefined\"!=typeof window&&null!==(e=window)&&void 0!==e&&null!==(t=e.navigator)&&void 0!==t&&t.maxTouchPoints?window.navigator.maxTouchPoints:0)>=5;return!!(n.match(/Mobi/)||n.match(/Android/)||r)||(!!ta().match(/DailyAnd\\//)||void 0)}function pa(){if(\"undefined\"!=typeof window){var e=ta();return va()?\"Safari\":e.indexOf(\"Edge\")>-1?\"Edge\":e.match(/Chrome\\//)?\"Chrome\":e.indexOf(\"Safari\")>-1||ga()?\"Safari\":e.indexOf(\"Firefox\")>-1?\"Firefox\":e.indexOf(\"MSIE\")>-1||e.indexOf(\".NET\")>-1?\"IE\":\"Unknown Browser\"}}function ha(){switch(pa()){case\"Chrome\":return fa();case\"Safari\":return ma();case\"Firefox\":return ya();case\"Edge\":return function(){var e=0,t=0;if(\"undefined\"!=typeof window){var n=ta().match(/Edge\\/(\\d+).(\\d+)/);if(n)try{e=parseInt(n[1]),t=parseInt(n[2])}catch(e){}}return{major:e,minor:t}}()}}function fa(){var e=0,t=0,n=0,r=0,i=!1;if(\"undefined\"!=typeof window){var o=ta(),a=o.match(/Chrome\\/(\\d+).(\\d+).(\\d+).(\\d+)/);if(a)try{e=parseInt(a[1]),t=parseInt(a[2]),n=parseInt(a[3]),r=parseInt(a[4]),i=o.indexOf(\"OPR/\")>-1}catch(e){}}return{major:e,minor:t,build:n,patch:r,opera:i}}function va(){return!!ta().match(/iPad|iPhone|iPod/i)&&ra()}function ga(){return ta().indexOf(\"AppleWebKit/605.1.15\")>-1}function ma(){var e=0,t=0,n=0;if(\"undefined\"!=typeof window){var r=ta().match(/Version\\/(\\d+).(\\d+)(.(\\d+))?/);if(r)try{e=parseInt(r[1]),t=parseInt(r[2]),n=parseInt(r[4])}catch(e){}else(va()||ga())&&(e=14,t=0,n=3)}return{major:e,minor:t,point:n}}function ya(){var e=0,t=0;if(\"undefined\"!=typeof window){var n=ta().match(/Firefox\\/(\\d+).(\\d+)/);if(n)try{e=parseInt(n[1]),t=parseInt(n[2])}catch(e){}}return{major:e,minor:t}}var _a=function(){function e(){t(this,e)}return o(e,[{key:\"addListenerForMessagesFromCallMachine\",value:function(e,t,n){Y()}},{key:\"addListenerForMessagesFromDailyJs\",value:function(e,t,n){Y()}},{key:\"sendMessageToCallMachine\",value:function(e,t,n,r){Y()}},{key:\"sendMessageToDailyJs\",value:function(e,t){Y()}},{key:\"removeListener\",value:function(e){Y()}}]),e}();function ba(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function wa(e){for(var t=1;t0&&void 0!==arguments[0]?arguments[0]:{},r=n.data,i=n.mergeStrategy,o=void 0===i?Ta:i;t(this,e),e._validateMergeStrategy(o),e._validateData(r,o),this.mergeStrategy=o,this.data=r}return o(e,[{key:\"isNoOp\",value:function(){return e.isNoOpUpdate(this.data,this.mergeStrategy)}}],[{key:\"isNoOpUpdate\",value:function(e,t){return 0===Object.keys(e).length&&t===Pa}},{key:\"_validateMergeStrategy\",value:function(e){if(!Oa.includes(e))throw Error(\"Unrecognized mergeStrategy provided. Options are: [\".concat(Oa,\"]\"))}},{key:\"_validateData\",value:function(e,t){if(!function(e){if(null==e||\"object\"!==n(e))return!1;var t=Object.getPrototypeOf(e);return null==t||t===Object.prototype}(e))throw Error(\"Meeting session data must be a plain (map-like) object\");var r;try{if(r=JSON.stringify(e),t===Ta){var i=JSON.parse(r);D(i,e)||console.warn(\"The meeting session data provided will be modified when serialized.\",i,e)}else if(t===Pa)for(var o in e)if(Object.hasOwnProperty.call(e,o)&&void 0!==e[o]){var a=JSON.parse(JSON.stringify(e[o]));D(e[o],a)||console.warn(\"At least one key in the meeting session data provided will be modified when serialized.\",a,e[o])}}catch(e){throw Error(\"Meeting session data must be serializable to JSON: \".concat(e))}if(r.length>Jo)throw Error(\"Meeting session data is too large (\".concat(r.length,\" characters). Maximum size suppported is \").concat(Jo,\".\"))}}]),e}();function ja(e,t,n){return ja=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if(\"function\"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&s(i,n.prototype),i},ja.apply(null,arguments)}function La(e){var t=\"function\"==typeof Map?new Map:void 0;return La=function(e){if(null===e||(n=e,-1===Function.toString.call(n).indexOf(\"[native code]\")))return e;var n;if(\"function\"!=typeof e)throw new TypeError(\"Super expression must either be null or a function\");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return ja(e,arguments,u(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),s(r,e)},La(e)}function xa(e){var t=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if(\"function\"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=u(e);if(t){var i=u(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return l(this,n)}}function Ia(e){var t,n=null===(t=window._daily)||void 0===t?void 0:t.pendings;if(n){var r=n.indexOf(e);-1!==r&&n.splice(r,1)}}var Da=function(){function e(n){t(this,e),this._currentLoad=null,this._callClientId=n}return o(e,[{key:\"load\",value:function(){var e,t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;if(this.loaded)return window._daily.instances[this._callClientId].callMachine.reset(),void r(!0);e=this._callClientId,window._daily.pendings.push(e),this._currentLoad&&this._currentLoad.cancel(),this._currentLoad=new Na(n,(function(){r(!1)}),(function(e,n){n||Ia(t._callClientId),i(e,n)})),this._currentLoad.start()}},{key:\"cancel\",value:function(){this._currentLoad&&this._currentLoad.cancel(),Ia(this._callClientId)}},{key:\"loaded\",get:function(){return this._currentLoad&&this._currentLoad.succeeded}}]),e}(),Na=function(){function e(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;t(this,e),this._attemptsRemaining=3,this._currentAttempt=null,this._dailyConfig=n,this._successCallback=r,this._failureCallback=i}return o(e,[{key:\"start\",value:function(){var e=this;if(!this._currentAttempt){this._currentAttempt=new Ba(this._dailyConfig,this._successCallback,(function t(n){e._currentAttempt.cancelled||(e._attemptsRemaining--,e._failureCallback(n,e._attemptsRemaining>0),e._attemptsRemaining<=0||setTimeout((function(){e._currentAttempt.cancelled||(e._currentAttempt=new Ba(e._dailyConfig,e._successCallback,t),e._currentAttempt.start())}),3e3))})),this._currentAttempt.start()}}},{key:\"cancel\",value:function(){this._currentAttempt&&this._currentAttempt.cancel()}},{key:\"cancelled\",get:function(){return this._currentAttempt&&this._currentAttempt.cancelled}},{key:\"succeeded\",get:function(){return this._currentAttempt&&this._currentAttempt.succeeded}}]),e}(),Fa=function(){c(n,La(Error));var e=xa(n);function n(){return t(this,n),e.apply(this,arguments)}return o(n)}(),Ra=2e4,Ba=function(){function e(n,r,i){t(this,e),this._loadAttemptImpl=na()||!n.avoidEval?new Ua(n,r,i):new Va(n,r,i)}var n;return o(e,[{key:\"start\",value:(n=h((function*(){return this._loadAttemptImpl.start()})),function(){return n.apply(this,arguments)})},{key:\"cancel\",value:function(){this._loadAttemptImpl.cancel()}},{key:\"cancelled\",get:function(){return this._loadAttemptImpl.cancelled}},{key:\"succeeded\",get:function(){return this._loadAttemptImpl.succeeded}}]),e}(),Ua=function(){function e(n,r,i){t(this,e),this.cancelled=!1,this.succeeded=!1,this._networkTimedOut=!1,this._networkTimeout=null,this._iosCache=\"undefined\"!=typeof iOSCallObjectBundleCache&&iOSCallObjectBundleCache,this._refetchHeaders=null,this._dailyConfig=n,this._successCallback=r,this._failureCallback=i}var n,r,i,a;return o(e,[{key:\"start\",value:(a=h((function*(){var e=X(this._dailyConfig);!(yield this._tryLoadFromIOSCache(e))&&this._loadFromNetwork(e)})),function(){return a.apply(this,arguments)})},{key:\"cancel\",value:function(){clearTimeout(this._networkTimeout),this.cancelled=!0}},{key:\"_tryLoadFromIOSCache\",value:(i=h((function*(e){if(!this._iosCache)return!1;try{var t=yield this._iosCache.get(e);return!!this.cancelled||!!t&&(t.code?(Function('\"use strict\";'+t.code)(),this.succeeded=!0,this._successCallback(),!0):(this._refetchHeaders=t.refetchHeaders,!1))}catch(e){return!1}})),function(e){return i.apply(this,arguments)})},{key:\"_loadFromNetwork\",value:(r=h((function*(e){var t=this;this._networkTimeout=setTimeout((function(){t._networkTimedOut=!0,t._failureCallback({msg:\"Timed out (>\".concat(Ra,\" ms) when loading call object bundle \").concat(e),type:\"timeout\"})}),Ra);try{var n=this._refetchHeaders?{headers:this._refetchHeaders}:{},r=yield fetch(e,n);if(clearTimeout(this._networkTimeout),this.cancelled||this._networkTimedOut)throw new Fa;var i=yield this._getBundleCodeFromResponse(e,r);if(this.cancelled)throw new Fa;Function('\"use strict\";'+i)(),this._iosCache&&this._iosCache.set(e,i,r.headers),this.succeeded=!0,this._successCallback()}catch(t){if(clearTimeout(this._networkTimeout),t instanceof Fa||this.cancelled||this._networkTimedOut)return;this._failureCallback({msg:\"Failed to load call object bundle \".concat(e,\": \").concat(t),type:t.message})}})),function(e){return r.apply(this,arguments)})},{key:\"_getBundleCodeFromResponse\",value:(n=h((function*(e,t){if(t.ok)return yield t.text();if(this._iosCache&&304===t.status)return(yield this._iosCache.renew(e,t.headers)).code;throw new Error(\"Received \".concat(t.status,\" response\"))})),function(e,t){return n.apply(this,arguments)})}]),e}(),Va=function(){function e(n,r,i){t(this,e),this.cancelled=!1,this.succeeded=!1,this._dailyConfig=n,this._successCallback=r,this._failureCallback=i,this._attemptId=Q(),this._networkTimeout=null,this._scriptElement=null}return o(e,[{key:\"start\",value:function(){window._dailyCallMachineLoadWaitlist||(window._dailyCallMachineLoadWaitlist=new Set);var e=X(this._dailyConfig);\"object\"===(\"undefined\"==typeof document?\"undefined\":n(document))?this._startLoading(e):this._failureCallback({msg:\"Call object bundle must be loaded in a DOM/web context\",type:\"missing context\"})}},{key:\"cancel\",value:function(){this._stopLoading(),this.cancelled=!0}},{key:\"_startLoading\",value:function(e){var t=this;this._signUpForCallMachineLoadWaitlist(),this._networkTimeout=setTimeout((function(){t._stopLoading(),t._failureCallback({msg:\"Timed out (>\".concat(Ra,\" ms) when loading call object bundle \").concat(e),type:\"timeout\"})}),Ra);var n=document.getElementsByTagName(\"head\")[0],r=document.createElement(\"script\");this._scriptElement=r,r.onload=function(){t._stopLoading(),t.succeeded=!0,t._successCallback()},r.onerror=function(e){t._stopLoading(),t._failureCallback({msg:\"Failed to load call object bundle \".concat(e.target.src),type:e.message})},r.src=e,n.appendChild(r)}},{key:\"_stopLoading\",value:function(){this._withdrawFromCallMachineLoadWaitlist(),clearTimeout(this._networkTimeout),this._scriptElement&&(this._scriptElement.onload=null,this._scriptElement.onerror=null)}},{key:\"_signUpForCallMachineLoadWaitlist\",value:function(){window._dailyCallMachineLoadWaitlist.add(this._attemptId)}},{key:\"_withdrawFromCallMachineLoadWaitlist\",value:function(){window._dailyCallMachineLoadWaitlist.delete(this._attemptId)}}]),e}(),Ja=function(e,t,n){return!0===za(e.local,t,n)},$a=function(e,t,n){return e.local.streams&&e.local.streams[t]&&e.local.streams[t].stream&&e.local.streams[t].stream[\"get\".concat(\"video\"===n?\"Video\":\"Audio\",\"Tracks\")]()[0]},qa=function(e,t,n,r){var i=Wa(e,t,n,r);return i&&i.pendingTrack},za=function(e,t,n){if(!e)return!1;var r=function(e){switch(e){case\"avatar\":return!0;case\"staged\":return e;default:return!!e}},i=e.public.subscribedTracks;return i&&i[t]?-1===[\"cam-audio\",\"cam-video\",\"screen-video\",\"screen-audio\",\"rmpAudio\",\"rmpVideo\"].indexOf(n)&&i[t].custom?[!0,\"staged\"].includes(i[t].custom)?r(i[t].custom):r(i[t].custom[n]):r(i[t][n]):!i||r(i.ALL)},Wa=function(e,t,n,r){var i=Object.values(e.streams||{}).filter((function(e){return e.participantId===t&&e.type===n&&e.pendingTrack&&e.pendingTrack.kind===r})).sort((function(e,t){return new Date(t.starttime)-new Date(e.starttime)}));return i&&i[0]},Ha=function(e,t){var n=e.local.public.customTracks;if(n&&n[t])return n[t].track};function Ga(e,t){for(var n=t.getState(),r=0,i=[\"cam\",\"screen\"];r=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\")}var o,a=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw o}}}}function Za(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\")}var o,a=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw o}}}}function rs(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\")}var o,a=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw o}}}}function ms(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n49)return console.error(\"grid.maxTilesPerPage can't be larger than 49 without sacrificing browser performance. Please contact us at https://www.daily.co/contact to talk about your use case.\"),!1}if(\"minTilesPerPage\"in t){if(!Number.isInteger(t.minTilesPerPage))return console.error(\"grid.minTilesPerPage should be an integer. You passed \".concat(t.minTilesPerPage,\".\")),!1;if(t.minTilesPerPage<1)return console.error(\"grid.minTilesPerPage can't be lower than 1.\"),!1;if(\"maxTilesPerPage\"in t&&t.minTilesPerPage>t.maxTilesPerPage)return console.error(\"grid.minTilesPerPage can't be higher than grid.maxTilesPerPage.\"),!1}}return!0},help:\"unsupported layoutConfig. Check error logs for detailed info.\"},receiveSettings:{validate:function(e){return $s(e,{allowAllParticipantsKey:!1})},help:Ys({allowAllParticipantsKey:!1})},sendSettings:{validate:function(e,t){return!!function(e,t){try{return t.validateUpdateSendSettings(e),!0}catch(e){return console.error(\"Failed to validate send settings\",e),!1}}(e,t)&&(t._preloadCache.sendSettings=e,!0)},help:\"Invalid sendSettings provided. Check error logs for detailed info.\"},inputSettings:{validate:function(e,t){var n;return!!qs(e)&&(t._inputSettings||(t._inputSettings={}),zs(e,null===(n=t.properties)||void 0===n?void 0:n.dailyConfig,t._sharedTracks),t._updatePreloadCacheInputSettings(e,!0),!0)},help:Qs()},layout:{validate:function(e){return\"custom-v1\"===e||\"browser\"===e||\"none\"===e},help:'layout may only be set to \"custom-v1\"',queryString:\"layout\"},emb:{queryString:\"emb\"},embHref:{queryString:\"embHref\"},dailyJsVersion:{queryString:\"dailyJsVersion\"},proxy:{queryString:\"proxy\"},strictMode:!0,allowMultipleCallInstances:!0},As={styles:{validate:function(e){for(var t in e)if(\"cam\"!==t&&\"screen\"!==t)return!1;if(e.cam)for(var n in e.cam)if(\"div\"!==n&&\"video\"!==n)return!1;if(e.screen)for(var r in e.screen)if(\"div\"!==r&&\"video\"!==r)return!1;return!0},help:\"styles format should be a subset of: { cam: {div: {}, video: {}}, screen: {div: {}, video: {}} }\"},setSubscribedTracks:{validate:function(e,t){if(t._preloadCache.subscribeToTracksAutomatically)return!1;var n=[!0,!1,\"staged\"];if(n.includes(e)||!na()&&\"avatar\"===e)return!0;var r=[\"audio\",\"video\",\"screenAudio\",\"screenVideo\",\"rmpAudio\",\"rmpVideo\"];return function e(t){var i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];for(var o in t)if(\"custom\"===o){if(!n.includes(t[o])&&!e(t[o],!0))return!1}else{var a=!i&&!r.includes(o),s=!n.includes(t[o]);if(a||s)return!1}return!0}(e)},help:\"setSubscribedTracks cannot be used when setSubscribeToTracksAutomatically is enabled, and should be of the form: \"+\"true\".concat(na()?\"\":\" | 'avatar'\",\" | false | 'staged' | { [audio: true|false|'staged'], [video: true|false|'staged'], [screenAudio: true|false|'staged'], [screenVideo: true|false|'staged'] }\")},setAudio:!0,setVideo:!0,setScreenShare:{validate:function(e){return!1===e},help:\"setScreenShare must be false, as it's only meant for stopping remote participants' screen shares\"},eject:!0,updatePermissions:{validate:function(e){for(var t=0,n=Object.entries(e);t1&&void 0!==arguments[1]?arguments[1]:{};if(t(this,ee),d(a(r=Z.call(this)),\"startListeningForDeviceChanges\",(function(){as(r.handleDeviceChange)})),d(a(r),\"stopListeningForDeviceChanges\",(function(){ss(r.handleDeviceChange)})),d(a(r),\"handleDeviceChange\",(function(e){e=e.map((function(e){return JSON.parse(JSON.stringify(e))})),r.emitDailyJSEvent({action:\"available-devices-updated\",availableDevices:e})})),d(a(r),\"handleNativeAppStateChange\",function(){var e=h((function*(e){if(\"destroyed\"===e)return console.warn(\"App has been destroyed before leaving the meeting. Cleaning up all the resources!\"),void(yield r.destroy());var t=\"active\"===e;r.disableReactNativeAutoDeviceManagement(\"video\")||(t?r.camUnmutedBeforeLosingNativeActiveState&&r.setLocalVideo(!0):(r.camUnmutedBeforeLosingNativeActiveState=r.localVideo(),r.camUnmutedBeforeLosingNativeActiveState&&r.setLocalVideo(!1)))}));return function(t){return e.apply(this,arguments)}}()),d(a(r),\"handleNativeAudioFocusChange\",(function(e){r.disableReactNativeAutoDeviceManagement(\"audio\")||(r._hasNativeAudioFocus=e,r.toggleParticipantAudioBasedOnNativeAudioFocus(),r._hasNativeAudioFocus?r.micUnmutedBeforeLosingNativeAudioFocus&&r.setLocalAudio(!0):(r.micUnmutedBeforeLosingNativeAudioFocus=r.localAudio(),r.setLocalAudio(!1)))})),d(a(r),\"handleNativeSystemScreenCaptureStop\",(function(){r.stopScreenShare()})),r.strictMode=void 0===o.strictMode||o.strictMode,r.allowMultipleCallInstances=null!==(n=o.allowMultipleCallInstances)&&void 0!==n&&n,Object.keys(ys).length&&(r._logDuplicateInstanceAttempt(),!r.allowMultipleCallInstances)){if(r.strictMode)throw new Error(\"Duplicate DailyIframe instances are not allowed\");console.warn(\"Using strictMode: false to allow multiple call instances is now deprecated. Set `allowMultipleCallInstances: true`\")}if(window._daily||(window._daily={pendings:[],instances:{}}),r.callClientId=Q(),i=a(r),ys[i.callClientId]=i,window._daily.instances[r.callClientId]={},r._sharedTracks={},window._daily.instances[r.callClientId].tracks=r._sharedTracks,o.dailyJsVersion=ee.version(),r._iframe=e,r._callObjectMode=\"none\"===o.layout&&!r._iframe,r._preloadCache={subscribeToTracksAutomatically:!0,outputDeviceId:null,inputSettings:null,sendSettings:null,videoTrackForNetworkConnectivityTest:null,videoTrackForConnectionQualityTest:null},void 0!==o.showLocalVideo?r._callObjectMode?console.error(\"showLocalVideo is not available in call object mode\"):r._showLocalVideo=!!o.showLocalVideo:r._showLocalVideo=!0,void 0!==o.showParticipantsBar?r._callObjectMode?console.error(\"showParticipantsBar is not available in call object mode\"):r._showParticipantsBar=!!o.showParticipantsBar:r._showParticipantsBar=!0,void 0!==o.customIntegrations?r._callObjectMode?console.error(\"customIntegrations is not available in call object mode\"):r._customIntegrations=o.customIntegrations:r._customIntegrations={},void 0!==o.customTrayButtons?r._callObjectMode?console.error(\"customTrayButtons is not available in call object mode\"):r._customTrayButtons=o.customTrayButtons:r._customTrayButtons={},void 0!==o.activeSpeakerMode?r._callObjectMode?console.error(\"activeSpeakerMode is not available in call object mode\"):r._activeSpeakerMode=!!o.activeSpeakerMode:r._activeSpeakerMode=!1,o.receiveSettings?r._callObjectMode?r._receiveSettings=o.receiveSettings:console.error(\"receiveSettings is only available in call object mode\"):r._receiveSettings={},r.validateProperties(o),r.properties=fs({},o),r._inputSettings||(r._inputSettings={}),r._callObjectLoader=r._callObjectMode?new Da(r.callClientId):null,r._callState=Zr,r._isPreparingToJoin=!1,r._accessState={access:pi},r._meetingSessionSummary={},r._finalSummaryOfPrevSession={},r._meetingSessionState=ic(ws,r._callObjectMode),r._nativeInCallAudioMode=_s,r._participants={},r._isScreenSharing=!1,r._participantCounts=ks,r._rmpPlayerState={},r._waitingParticipants={},r._network={threshold:\"good\",quality:100},r._activeSpeaker={},r._localAudioLevel=0,r._isLocalAudioLevelObserverRunning=!1,r._remoteParticipantsAudioLevel={},r._isRemoteParticipantsAudioLevelObserverRunning=!1,r._maxAppMessageSize=Vo,r._messageChannel=na()?new Ea:new Sa,r._iframe&&(r._iframe.requestFullscreen?r._iframe.addEventListener(\"fullscreenchange\",(function(){document.fullscreenElement===r._iframe?(r.emitDailyJSEvent({action:Ao}),r.sendMessageToCallMachine({action:Ao})):(r.emitDailyJSEvent({action:jo}),r.sendMessageToCallMachine({action:jo}))})):r._iframe.webkitRequestFullscreen&&r._iframe.addEventListener(\"webkitfullscreenchange\",(function(){document.webkitFullscreenElement===r._iframe?(r.emitDailyJSEvent({action:Ao}),r.sendMessageToCallMachine({action:Ao})):(r.emitDailyJSEvent({action:jo}),r.sendMessageToCallMachine({action:jo}))}))),na()){var s=r.nativeUtils();s.addAudioFocusChangeListener&&s.removeAudioFocusChangeListener&&s.addAppStateChangeListener&&s.removeAppStateChangeListener&&s.addSystemScreenCaptureStopListener&&s.removeSystemScreenCaptureStopListener||console.warn(\"expected (add|remove)(AudioFocusChange|AppActiveStateChange|SystemScreenCaptureStop)Listener to be available in React Native\"),r._hasNativeAudioFocus=!0,s.addAudioFocusChangeListener(r.handleNativeAudioFocusChange),s.addAppStateChangeListener(r.handleNativeAppStateChange),s.addSystemScreenCaptureStopListener(r.handleNativeSystemScreenCaptureStop)}return r._callObjectMode&&r.startListeningForDeviceChanges(),r._messageChannel.addListenerForMessagesFromCallMachine(r.handleMessageFromCallMachine,r.callClientId,a(r)),r}return o(ee,[{key:\"destroy\",value:(Y=h((function*(){var e,t;try{yield this.leave()}catch(e){}var n=this._iframe;if(n){var r=n.parentElement;r&&r.removeChild(n)}if(this._messageChannel.removeListener(this.handleMessageFromCallMachine),na()){var i=this.nativeUtils();i.removeAudioFocusChangeListener(this.handleNativeAudioFocusChange),i.removeAppStateChangeListener(this.handleNativeAppStateChange),i.removeSystemScreenCaptureStopListener(this.handleNativeSystemScreenCaptureStop)}this._callObjectMode&&this.stopListeningForDeviceChanges(),this.resetMeetingDependentVars(),this._destroyed=!0,this.emitDailyJSEvent({action:\"call-instance-destroyed\"}),delete ys[this.callClientId],(null===(e=window)||void 0===e||null===(t=e._daily)||void 0===t?void 0:t.instances)&&delete window._daily.instances[this.callClientId],this.strictMode&&(this.callClientId=void 0)})),function(){return Y.apply(this,arguments)})},{key:\"isDestroyed\",value:function(){return!!this._destroyed}},{key:\"loadCss\",value:function(e){var t=e.bodyClass,n=e.cssFile,r=e.cssText;return Us(),this.sendMessageToCallMachine({action:\"load-css\",cssFile:this.absoluteUrl(n),bodyClass:t,cssText:r}),this}},{key:\"iframe\",value:function(){return Us(),this._iframe}},{key:\"meetingState\",value:function(){return this._callState}},{key:\"accessState\",value:function(){return Rs(this._callObjectMode,\"accessState()\"),this._accessState}},{key:\"participants\",value:function(){return this._participants}},{key:\"participantCounts\",value:function(){return this._participantCounts}},{key:\"waitingParticipants\",value:function(){return Rs(this._callObjectMode,\"waitingParticipants()\"),this._waitingParticipants}},{key:\"validateParticipantProperties\",value:function(e,t){for(var n in t){if(!As[n])throw new Error(\"unrecognized updateParticipant property \".concat(n));if(As[n].validate&&!As[n].validate(t[n],this,this._participants[e]))throw new Error(As[n].help)}}},{key:\"updateParticipant\",value:function(e,t){return this._participants.local&&this._participants.local.session_id===e&&(e=\"local\"),e&&t&&(this.validateParticipantProperties(e,t),this.sendMessageToCallMachine({action:\"update-participant\",id:e,properties:t})),this}},{key:\"updateParticipants\",value:function(e){var t=this._participants.local&&this._participants.local.session_id;for(var n in e)n===t&&(n=\"local\"),n&&e[n]&&this.validateParticipantProperties(n,e[n]);return this.sendMessageToCallMachine({action:\"update-participants\",participants:e}),this}},{key:\"updateWaitingParticipant\",value:(H=h((function*(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:\"\",r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(Rs(this._callObjectMode,\"updateWaitingParticipant()\"),xs(this._callState,\"updateWaitingParticipant()\"),\"string\"!=typeof t||\"object\"!==n(r))throw new Error(\"updateWaitingParticipant() must take an id string and a updates object\");return new Promise((function(n,i){e.sendMessageToCallMachine({action:\"daily-method-update-waiting-participant\",id:t,updates:r},(function(e){e.error&&i(e.error),e.id||i(new Error(\"unknown error in updateWaitingParticipant()\")),n({id:e.id})}))}))})),function(){return H.apply(this,arguments)})},{key:\"updateWaitingParticipants\",value:(W=h((function*(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(Rs(this._callObjectMode,\"updateWaitingParticipants()\"),xs(this._callState,\"updateWaitingParticipants()\"),\"object\"!==n(t))throw new Error(\"updateWaitingParticipants() must take a mapping between ids and update objects\");return new Promise((function(n,r){e.sendMessageToCallMachine({action:\"daily-method-update-waiting-participants\",updatesById:t},(function(e){e.error&&r(e.error),e.ids||r(new Error(\"unknown error in updateWaitingParticipants()\")),n({ids:e.ids})}))}))})),function(){return W.apply(this,arguments)})},{key:\"requestAccess\",value:(z=h((function*(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=t.access,r=void 0===n?{level:hi}:n,i=t.name,o=void 0===i?\"\":i;return Rs(this._callObjectMode,\"requestAccess()\"),xs(this._callState,\"requestAccess()\"),new Promise((function(t,n){e.sendMessageToCallMachine({action:\"daily-method-request-access\",access:r,name:o},(function(e){e.error&&n(e.error),e.access||n(new Error(\"unknown error in requestAccess()\")),t({access:e.access,granted:e.granted})}))}))})),function(){return z.apply(this,arguments)})},{key:\"localAudio\",value:function(){return this._participants.local?![\"blocked\",\"off\"].includes(this._participants.local.tracks.audio.state):null}},{key:\"localVideo\",value:function(){return this._participants.local?![\"blocked\",\"off\"].includes(this._participants.local.tracks.video.state):null}},{key:\"setLocalAudio\",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return\"forceDiscardTrack\"in t&&(na()?(console.warn(\"forceDiscardTrack option not supported in React Native; ignoring\"),t={}):e&&(console.warn(\"forceDiscardTrack option only supported when calling setLocalAudio(false); ignoring\"),t={})),this.sendMessageToCallMachine({action:\"local-audio\",state:e,options:t}),this}},{key:\"localScreenAudio\",value:function(){return this._participants.local?![\"blocked\",\"off\"].includes(this._participants.local.tracks.screenAudio.state):null}},{key:\"localScreenVideo\",value:function(){return this._participants.local?![\"blocked\",\"off\"].includes(this._participants.local.tracks.screenVideo.state):null}},{key:\"updateScreenShare\",value:function(e){if(this._isScreenSharing)return this.sendMessageToCallMachine({action:\"local-screen-update\",options:e}),this;console.warn(\"There is no screen share in progress. Try calling startScreenShare first.\")}},{key:\"setLocalVideo\",value:function(e){return this.sendMessageToCallMachine({action:\"local-video\",state:e}),this}},{key:\"_setAllowLocalAudio\",value:function(e){if(this._preloadCache.allowLocalAudio=e,this._callMachineInitialized)return this.sendMessageToCallMachine({action:\"set-allow-local-audio\",state:e}),this}},{key:\"_setAllowLocalVideo\",value:function(e){if(this._preloadCache.allowLocalVideo=e,this._callMachineInitialized)return this.sendMessageToCallMachine({action:\"set-allow-local-video\",state:e}),this}},{key:\"getReceiveSettings\",value:(q=h((function*(e){var t=this,r=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).showInheritedValues,i=void 0!==r&&r;if(Rs(this._callObjectMode,\"getReceiveSettings()\"),!this._callMachineInitialized)return this._receiveSettings;switch(n(e)){case\"string\":return new Promise((function(n){t.sendMessageToCallMachine({action:\"get-single-participant-receive-settings\",id:e,showInheritedValues:i},(function(e){n(e.receiveSettings)}))}));case\"undefined\":return this._receiveSettings;default:throw new Error('first argument to getReceiveSettings() must be a participant id (or \"base\"), or there should be no arguments')}})),function(e){return q.apply(this,arguments)})},{key:\"updateReceiveSettings\",value:($=h((function*(e){var t=this;if(Rs(this._callObjectMode,\"updateReceiveSettings()\"),!$s(e,{allowAllParticipantsKey:!0}))throw new Error(Ys({allowAllParticipantsKey:!0}));return xs(this._callState,\"updateReceiveSettings()\",\"To specify receive settings earlier, use the receiveSettings config property.\"),new Promise((function(n){t.sendMessageToCallMachine({action:\"update-receive-settings\",receiveSettings:e},(function(e){n({receiveSettings:e.receiveSettings})}))}))})),function(e){return $.apply(this,arguments)})},{key:\"_prepInputSettingsForSharing\",value:function(e,t){if(e){var n={};if(e.audio){var r,i,o,a;e.audio.settings&&(!Object.keys(e.audio.settings).length&&t||(n.audio={settings:fs({},e.audio.settings)})),t&&null!==(r=n.audio)&&void 0!==r&&null!==(i=r.settings)&&void 0!==i&&i.customTrack&&(n.audio.settings={customTrack:this._sharedTracks.audioTrack});var s=\"none\"===(null===(o=e.audio.processor)||void 0===o?void 0:o.type)&&(null===(a=e.audio.processor)||void 0===a?void 0:a._isDefaultWhenNone);if(e.audio.processor&&!s){var c=fs({},e.audio.processor);delete c._isDefaultWhenNone,n.audio=fs(fs({},n.audio),{},{processor:c})}}if(e.video){var l,u,d,p;e.video.settings&&(!Object.keys(e.video.settings).length&&t||(n.video={settings:fs({},e.video.settings)})),t&&null!==(l=n.video)&&void 0!==l&&null!==(u=l.settings)&&void 0!==u&&u.customTrack&&(n.video.settings={customTrack:this._sharedTracks.videoTrack});var h=\"none\"===(null===(d=e.video.processor)||void 0===d?void 0:d.type)&&(null===(p=e.video.processor)||void 0===p?void 0:p._isDefaultWhenNone);if(e.video.processor&&!h){var f=fs({},e.video.processor);delete f._isDefaultWhenNone,n.video=fs(fs({},n.video),{},{processor:f})}}return n}}},{key:\"getInputSettings\",value:function(){var e=this;return Us(),new Promise((function(t){t(e._getInputSettings())}))}},{key:\"_getInputSettings\",value:function(){var e,t,n,r,i,o,a,s,c={processor:{type:\"none\",_isDefaultWhenNone:!0}};this._inputSettings?(e=(null===(n=this._inputSettings)||void 0===n?void 0:n.video)||c,t=(null===(r=this._inputSettings)||void 0===r?void 0:r.audio)||c):(e=(null===(i=this._preloadCache)||void 0===i||null===(o=i.inputSettings)||void 0===o?void 0:o.video)||c,t=(null===(a=this._preloadCache)||void 0===a||null===(s=a.inputSettings)||void 0===s?void 0:s.audio)||c);var l={audio:t,video:e};return this._prepInputSettingsForSharing(l,!0)}},{key:\"_updatePreloadCacheInputSettings\",value:function(e,t){var n=this._inputSettings||{},r={};if(e.video){var i,o,a;if(r.video={},e.video.settings)r.video.settings={},t||e.video.settings.customTrack||null===(a=n.video)||void 0===a||!a.settings?r.video.settings=e.video.settings:r.video.settings=fs(fs({},n.video.settings),e.video.settings),Object.keys(r.video.settings).length||delete r.video.settings;else null!==(i=n.video)&&void 0!==i&&i.settings&&(r.video.settings=n.video.settings);e.video.processor?r.video.processor=e.video.processor:null!==(o=n.video)&&void 0!==o&&o.processor&&(r.video.processor=n.video.processor)}else n.video&&(r.video=n.video);if(e.audio){var s,c,l;if(r.audio={},e.audio.settings)r.audio.settings={},t||e.audio.settings.customTrack||null===(l=n.audio)||void 0===l||!l.settings?r.audio.settings=e.audio.settings:r.audio.settings=fs(fs({},n.audio.settings),e.audio.settings),Object.keys(r.audio.settings).length||delete r.audio.settings;else null!==(s=n.audio)&&void 0!==s&&s.settings&&(r.audio.settings=n.audio.settings);e.audio.processor?r.audio.processor=e.audio.processor:null!==(c=n.audio)&&void 0!==c&&c.processor&&(r.audio.processor=n.audio.processor)}else n.audio&&(r.audio=n.audio);this._maybeUpdateInputSettings(r)}},{key:\"_devicesFromInputSettings\",value:function(e){var t,n,r,i,o=(null==e||null===(t=e.video)||void 0===t||null===(n=t.settings)||void 0===n?void 0:n.deviceId)||null,a=(null==e||null===(r=e.audio)||void 0===r||null===(i=r.settings)||void 0===i?void 0:i.deviceId)||null,s=this._preloadCache.outputDeviceId||null;return{camera:o?{deviceId:o}:{},mic:a?{deviceId:a}:{},speaker:s?{deviceId:s}:{}}}},{key:\"updateInputSettings\",value:(J=h((function*(e){var t=this;return Us(),qs(e)?e.video||e.audio?(zs(e,this.properties.dailyConfig,this._sharedTracks),this._callObjectMode&&!this._callMachineInitialized?(this._updatePreloadCacheInputSettings(e,!0),this._getInputSettings()):new Promise((function(n,r){t.sendMessageToCallMachine({action:\"update-input-settings\",inputSettings:e},(function(i){if(i.error)r(i.error);else{if(i.returnPreloadCache)return t._updatePreloadCacheInputSettings(e,!0),void n(t._getInputSettings());t._maybeUpdateInputSettings(i.inputSettings),n(t._prepInputSettingsForSharing(i.inputSettings,!0))}}))}))):this._getInputSettings():(console.error(Qs()),Promise.reject(Qs()))})),function(e){return J.apply(this,arguments)})},{key:\"setBandwidth\",value:function(e){var t=e.kbs,n=e.trackConstraints;if(Us(),this._callMachineInitialized)return this.sendMessageToCallMachine({action:\"set-bandwidth\",kbs:t,trackConstraints:n}),this}},{key:\"getDailyLang\",value:function(){var e=this;if(Us(),this._callMachineInitialized)return new Promise((function(t){e.sendMessageToCallMachine({action:\"get-daily-lang\"},(function(e){delete e.action,delete e.callbackStamp,t(e)}))}))}},{key:\"setDailyLang\",value:function(e){return Us(),this.sendMessageToCallMachine({action:\"set-daily-lang\",lang:e}),this}},{key:\"setProxyUrl\",value:function(e){return this.sendMessageToCallMachine({action:\"set-proxy-url\",proxyUrl:e}),this}},{key:\"setIceConfig\",value:function(e){return this.sendMessageToCallMachine({action:\"set-ice-config\",iceConfig:e}),this}},{key:\"meetingSessionSummary\",value:function(){return[ii,oi].includes(this._callState)?this._finalSummaryOfPrevSession:this._meetingSessionSummary}},{key:\"getMeetingSession\",value:(V=h((function*(){var e=this;return console.warn(\"getMeetingSession() is deprecated: use meetingSessionSummary(), which will return immediately\"),xs(this._callState,\"getMeetingSession()\"),new Promise((function(t){e.sendMessageToCallMachine({action:\"get-meeting-session\"},(function(e){delete e.action,delete e.callbackStamp,t(e)}))}))})),function(){return V.apply(this,arguments)})},{key:\"meetingSessionState\",value:function(){return xs(this._callState,\"meetingSessionState\"),this._meetingSessionState}},{key:\"setMeetingSessionData\",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"replace\";Rs(this._callObjectMode,\"setMeetingSessionData()\"),xs(this._callState,\"setMeetingSessionData\");try{!function(e,t){new Aa({data:e,mergeStrategy:t})}(e,t)}catch(e){throw console.error(e),e}try{this.sendMessageToCallMachine({action:\"set-session-data\",data:e,mergeStrategy:t})}catch(e){throw new Error(\"Error setting meeting session data: \".concat(e))}}},{key:\"setUserName\",value:function(e,t){var n=this;return this.properties.userName=e,new Promise((function(r){n.sendMessageToCallMachine({action:\"set-user-name\",name:null!=e?e:\"\",thisMeetingOnly:na()||!!t&&!!t.thisMeetingOnly},(function(e){delete e.action,delete e.callbackStamp,r(e)}))}))}},{key:\"setUserData\",value:(U=h((function*(e){var t=this;try{Js(e)}catch(e){throw console.error(e),e}if(this.properties.userData=e,this._callMachineInitialized)return new Promise((function(n){try{t.sendMessageToCallMachine({action:\"set-user-data\",userData:e},(function(e){delete e.action,delete e.callbackStamp,n(e)}))}catch(e){throw new Error(\"Error setting user data: \".concat(e))}}))})),function(e){return U.apply(this,arguments)})},{key:\"validateAudioLevelInterval\",value:function(e){if(e&&(e<100||\"number\"!=typeof e))throw new Error(\"The interval must be a number greater than or equal to 100 milliseconds.\")}},{key:\"startLocalAudioLevelObserver\",value:function(e){var t=this;if(\"undefined\"==typeof AudioWorkletNode&&!na())throw new Error(\"startLocalAudioLevelObserver() is not supported on this browser\");if(this.validateAudioLevelInterval(e),this._callMachineInitialized)return this._isLocalAudioLevelObserverRunning=!0,new Promise((function(n,r){t.sendMessageToCallMachine({action:\"start-local-audio-level-observer\",interval:e},(function(e){t._isLocalAudioLevelObserverRunning=!e.error,e.error?r({error:e.error}):n()}))}));this._preloadCache.localAudioLevelObserver={enabled:!0,interval:e}}},{key:\"isLocalAudioLevelObserverRunning\",value:function(){return this._isLocalAudioLevelObserverRunning}},{key:\"stopLocalAudioLevelObserver\",value:function(){this._preloadCache.localAudioLevelObserver=null,this._localAudioLevel=0,this._isLocalAudioLevelObserverRunning=!1,this.sendMessageToCallMachine({action:\"stop-local-audio-level-observer\"})}},{key:\"startRemoteParticipantsAudioLevelObserver\",value:function(e){var t=this;if(this.validateAudioLevelInterval(e),this._callMachineInitialized)return this._isRemoteParticipantsAudioLevelObserverRunning=!0,new Promise((function(n,r){t.sendMessageToCallMachine({action:\"start-remote-participants-audio-level-observer\",interval:e},(function(e){t._isRemoteParticipantsAudioLevelObserverRunning=!e.error,e.error?r({error:e.error}):n()}))}));this._preloadCache.remoteParticipantsAudioLevelObserver={enabled:!0,interval:e}}},{key:\"isRemoteParticipantsAudioLevelObserverRunning\",value:function(){return this._isRemoteParticipantsAudioLevelObserverRunning}},{key:\"stopRemoteParticipantsAudioLevelObserver\",value:function(){this._preloadCache.remoteParticipantsAudioLevelObserver=null,this._remoteParticipantsAudioLevel={},this._isRemoteParticipantsAudioLevelObserverRunning=!1,this.sendMessageToCallMachine({action:\"stop-remote-participants-audio-level-observer\"})}},{key:\"startCamera\",value:(B=h((function*(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(Rs(this._callObjectMode,\"startCamera()\"),Ds(this._callState,this._isPreparingToJoin,\"startCamera()\",\"Did you mean to use setLocalAudio() and/or setLocalVideo() instead?\"),this.needsLoad())try{yield this.load(t)}catch(e){return Promise.reject(e)}else{if(this._didPreAuth){if(t.url&&t.url!==this.properties.url)return console.error(\"url in startCamera() is different than the one used in preAuth()\"),Promise.reject();if(t.token&&t.token!==this.properties.token)return console.error(\"token in startCamera() is different than the one used in preAuth()\"),Promise.reject()}this.validateProperties(t),this.properties=fs(fs({},this.properties),t)}return new Promise((function(t){e._preloadCache.inputSettings=e._prepInputSettingsForSharing(e._inputSettings,!1),e.sendMessageToCallMachine({action:\"start-camera\",properties:Ls(e.properties,e.callClientId),preloadCache:Ls(e._preloadCache,e.callClientId)},(function(e){t({camera:e.camera,mic:e.mic,speaker:e.speaker})}))}))})),function(){return B.apply(this,arguments)})},{key:\"validateCustomTrack\",value:function(e,t,n){if(n&&n.length>50)throw new Error(\"Custom track `trackName` must not be more than 50 characters\");if(t&&\"music\"!==t&&\"speech\"!==t&&!(t instanceof Object))throw new Error(\"Custom track `mode` must be either `music` | `speech` | `DailyMicAudioModeSettings` or `undefined`\");if(!!n&&[\"cam-audio\",\"cam-video\",\"screen-video\",\"screen-audio\",\"rmpAudio\",\"rmpVideo\",\"customVideoDefaults\"].includes(n))throw new Error(\"Custom track `trackName` must not match a track name already used by daily: cam-audio, cam-video, customVideoDefaults, screen-video, screen-audio, rmpAudio, rmpVideo\");if(!(e instanceof MediaStreamTrack))throw new Error(\"Custom tracks provided must be instances of MediaStreamTrack\")}},{key:\"startCustomTrack\",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{track:track,mode:mode,trackName:trackName};return Us(),xs(this._callState,\"startCustomTrack()\"),this.validateCustomTrack(t.track,t.mode,t.trackName),new Promise((function(n,r){e._sharedTracks.customTrack=t.track,t.track=Ho,e.sendMessageToCallMachine({action:\"start-custom-track\",properties:t},(function(e){e.error?r({error:e.error}):n(e.mediaTag)}))}))}},{key:\"stopCustomTrack\",value:function(e){var t=this;return Us(),xs(this._callState,\"stopCustomTrack()\"),new Promise((function(n){t.sendMessageToCallMachine({action:\"stop-custom-track\",mediaTag:e},(function(e){n(e.mediaTag)}))}))}},{key:\"setCamera\",value:function(e){var t=this;return Vs(),Ns(this._callMachineInitialized,\"setCamera()\"),new Promise((function(n){t.sendMessageToCallMachine({action:\"set-camera\",cameraDeviceId:e},(function(e){n({device:e.device})}))}))}},{key:\"setAudioDevice\",value:(R=h((function*(e){return Vs(),this.nativeUtils().setAudioDevice(e),{deviceId:yield this.nativeUtils().getAudioDevice()}})),function(e){return R.apply(this,arguments)})},{key:\"cycleCamera\",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new Promise((function(n){e.sendMessageToCallMachine({action:\"cycle-camera\",properties:t},(function(e){n({device:e.device})}))}))}},{key:\"cycleMic\",value:function(){var e=this;return Us(),new Promise((function(t){e.sendMessageToCallMachine({action:\"cycle-mic\"},(function(e){t({device:e.device})}))}))}},{key:\"getCameraFacingMode\",value:function(){var e=this;return Vs(),new Promise((function(t){e.sendMessageToCallMachine({action:\"get-camera-facing-mode\"},(function(e){t(e.facingMode)}))}))}},{key:\"setInputDevicesAsync\",value:(F=h((function*(e){var t=this,n=e.audioDeviceId,r=e.videoDeviceId,i=e.audioSource,o=e.videoSource;if(Us(),void 0!==i&&(n=i),void 0!==o&&(r=o),\"boolean\"==typeof n&&(this._setAllowLocalAudio(n),n=void 0),\"boolean\"==typeof r&&(this._setAllowLocalVideo(r),r=void 0),!n&&!r)return yield this.getInputDevices();var a={};return n&&(n instanceof MediaStreamTrack?(this._sharedTracks.audioTrack=n,n=Ho,a.audio={settings:{customTrack:n}}):(delete this._sharedTracks.audioTrack,a.audio={settings:{deviceId:n}})),r&&(r instanceof MediaStreamTrack?(this._sharedTracks.videoTrack=r,r=Ho,a.video={settings:{customTrack:r}}):(delete this._sharedTracks.videoTrack,a.video={settings:{deviceId:r}})),this._callObjectMode&&this.needsLoad()?(this._updatePreloadCacheInputSettings(a,!1),this._devicesFromInputSettings(this._inputSettings)):new Promise((function(e){t.sendMessageToCallMachine({action:\"set-input-devices\",audioDeviceId:n,videoDeviceId:r},(function(n){if(delete n.action,delete n.callbackStamp,n.returnPreloadCache)return t._updatePreloadCacheInputSettings(a,!1),void e(t._devicesFromInputSettings(t._inputSettings));e(n)}))}))})),function(e){return F.apply(this,arguments)})},{key:\"setOutputDeviceAsync\",value:(N=h((function*(e){var t=this,n=e.outputDeviceId;return Us(),n&&(this._preloadCache.outputDeviceId=n),this._callObjectMode&&this.needsLoad()?this._devicesFromInputSettings(this._inputSettings):new Promise((function(e){t.sendMessageToCallMachine({action:\"set-output-device\",outputDeviceId:n},(function(n){delete n.action,delete n.callbackStamp,n.returnPreloadCache?e(t._devicesFromInputSettings(t._inputSettings)):e(n)}))}))})),function(e){return N.apply(this,arguments)})},{key:\"getInputDevices\",value:(I=h((function*(){var e=this;return this._callObjectMode&&this.needsLoad()?this._devicesFromInputSettings(this._inputSettings):new Promise((function(t){e.sendMessageToCallMachine({action:\"get-input-devices\"},(function(n){n.returnPreloadCache?t(e._devicesFromInputSettings(e._inputSettings)):t({camera:n.camera,mic:n.mic,speaker:n.speaker})}))}))})),function(){return I.apply(this,arguments)})},{key:\"nativeInCallAudioMode\",value:function(){return Vs(),this._nativeInCallAudioMode}},{key:\"setNativeInCallAudioMode\",value:function(e){if(Vs(),[_s,bs].includes(e)){if(e!==this._nativeInCallAudioMode)return this._nativeInCallAudioMode=e,!this.disableReactNativeAutoDeviceManagement(\"audio\")&&Is(this._callState,this._isPreparingToJoin)&&this.nativeUtils().setAudioMode(this._nativeInCallAudioMode),this}else console.error(\"invalid in-call audio mode specified: \",e)}},{key:\"preAuth\",value:(x=h((function*(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(Rs(this._callObjectMode,\"preAuth()\"),Ds(this._callState,this._isPreparingToJoin,\"preAuth()\"),this.needsLoad()&&(yield this.load(t)),!t.url)throw new Error(\"preAuth() requires at least a url to be provided\");return this.validateProperties(t),this.properties=fs(fs({},this.properties),t),new Promise((function(t,n){e._preloadCache.inputSettings=e._prepInputSettingsForSharing(e._inputSettings,!1),e.sendMessageToCallMachine({action:\"daily-method-preauth\",properties:Ls(e.properties,e.callClientId),preloadCache:Ls(e._preloadCache,e.callClientId)},(function(r){return r.error?n(r.error):r.access?(e._didPreAuth=!0,void t({access:r.access})):n(new Error(\"unknown error in preAuth()\"))}))}))})),function(){return x.apply(this,arguments)})},{key:\"load\",value:(L=h((function*(e){var t=this;if(this.needsLoad()){if(this._destroyed&&(this._logUseAfterDestroy(),this.strictMode))throw new Error(\"Use after destroy\");if(e&&(this.validateProperties(e),this.properties=fs(fs({},this.properties),e)),!this._callObjectMode&&!this.properties.url)throw new Error(\"can't load iframe meeting because url property isn't set\");return this._updateCallState(ei),this.emitDailyJSEvent({action:Bi}),this._callObjectMode?new Promise((function(e,n){t._callObjectLoader.cancel();var r=Date.now();t._callObjectLoader.load(t.properties.dailyConfig,(function(n){t._bundleLoadTime=n?\"no-op\":Date.now()-r,t._updateCallState(ti),n&&t.emitDailyJSEvent({action:Vi}),e()}),(function(e,r){if(t.emitDailyJSEvent({action:Ui}),!r){t._updateCallState(oi),t.resetMeetingDependentVars();var i={action:Uo,errorMsg:e.msg,error:{type:\"connection-error\",msg:\"Failed to load call object bundle.\",details:{on:\"load\",sourceError:e,bundleUrl:X(t.properties.dailyConfig)}}};t._maybeSendToSentry(i),t.emitDailyJSEvent(i),n(e.msg)}}))})):(this._iframe.src=K(this.assembleMeetingUrl(),this.properties.dailyConfig),new Promise((function(e,n){t._loadedCallback=function(r){t._callState!==oi?(t._updateCallState(ti),(t.properties.cssFile||t.properties.cssText)&&t.loadCss(t.properties),e()):n(r)}})))}})),function(e){return L.apply(this,arguments)})},{key:\"join\",value:(j=h((function*(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._testCallInProgress&&this.stopTestCallQuality();var n=!1;if(this.needsLoad()){this.updateIsPreparingToJoin(!0);try{yield this.load(t)}catch(e){return this.updateIsPreparingToJoin(!1),Promise.reject(e)}}else{if(n=!(!this.properties.cssFile&&!this.properties.cssText),this._didPreAuth){if(t.url&&t.url!==this.properties.url)return console.error(\"url in join() is different than the one used in preAuth()\"),this.updateIsPreparingToJoin(!1),Promise.reject();if(t.token&&t.token!==this.properties.token)return console.error(\"token in join() is different than the one used in preAuth()\"),this.updateIsPreparingToJoin(!1),Promise.reject()}if(t.url&&!this._callObjectMode&&t.url&&t.url!==this.properties.url)return console.error(\"url in join() is different than the one used in load() (\".concat(this.properties.url,\" -> \").concat(t.url,\")\")),this.updateIsPreparingToJoin(!1),Promise.reject();this.validateProperties(t),this.properties=fs(fs({},this.properties),t)}return void 0!==t.showLocalVideo&&(this._callObjectMode?console.error(\"showLocalVideo is not available in callObject mode\"):this._showLocalVideo=!!t.showLocalVideo),void 0!==t.showParticipantsBar&&(this._callObjectMode?console.error(\"showParticipantsBar is not available in callObject mode\"):this._showParticipantsBar=!!t.showParticipantsBar),this._callState===ri||this._callState===ni?(console.warn(\"already joined meeting, call leave() before joining again\"),void this.updateIsPreparingToJoin(!1)):(this._updateCallState(ni,!1),this.emitDailyJSEvent({action:qi}),this._preloadCache.inputSettings=this._prepInputSettingsForSharing(this._inputSettings||{},!1),this.sendMessageToCallMachine({action:\"join-meeting\",properties:Ls(this.properties,this.callClientId),preloadCache:Ls(this._preloadCache,this.callClientId)}),new Promise((function(t,r){e._joinedCallback=function(i,o){if(e._callState!==oi){if(e._updateCallState(ri),i)for(var a in i){if(e._callObjectMode){var s=e._callMachine().store;Ga(i[a],s),Qa(i[a],s),Ka(i[a],e._participants[a],s)}e._participants[a]=fs({},i[a]),e.toggleParticipantAudioBasedOnNativeAudioFocus()}n&&e.loadCss(e.properties),t(i)}else r(o)}})))})),function(){return j.apply(this,arguments)})},{key:\"leave\",value:(A=h((function*(){var e=this;return this._testCallInProgress&&this.stopTestCallQuality(),new Promise((function(t){e._callState===ii||e._callState===oi?t():e._callObjectLoader&&!e._callObjectLoader.loaded?(e._callObjectLoader.cancel(),e._updateCallState(ii),e.resetMeetingDependentVars(),e.emitDailyJSEvent({action:ii}),t()):(e._resolveLeave=t,e.sendMessageToCallMachine({action:\"leave-meeting\"}))}))})),function(){return A.apply(this,arguments)})},{key:\"startScreenShare\",value:(O=h((function*(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(Ns(this._callMachineInitialized,\"startScreenShare()\"),t.screenVideoSendSettings&&this._validateVideoSendSettings(\"screenVideo\",t.screenVideoSendSettings),t.mediaStream&&(this._sharedTracks.screenMediaStream=t.mediaStream,t.mediaStream=Ho),\"undefined\"!=typeof DailyNativeUtils&&void 0!==DailyNativeUtils.isIOS&&DailyNativeUtils.isIOS){var n=this.nativeUtils();if(yield n.isScreenBeingCaptured())return void this.emitDailyJSEvent({action:Bo,type:\"screen-share-error\",errorMsg:\"Could not start the screen sharing. The screen is already been captured!\"});n.setSystemScreenCaptureStartCallback((function(){n.setSystemScreenCaptureStartCallback(null),e.sendMessageToCallMachine({action:qo,captureOptions:t})})),n.presentSystemScreenCapturePrompt()}else this.sendMessageToCallMachine({action:qo,captureOptions:t})})),function(){return O.apply(this,arguments)})},{key:\"stopScreenShare\",value:function(){Ns(this._callMachineInitialized,\"stopScreenShare()\"),this.sendMessageToCallMachine({action:\"local-screen-stop\"})}},{key:\"startRecording\",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.type;if(t&&\"cloud\"!==t&&\"raw-tracks\"!==t&&\"local\"!==t)throw new Error(\"invalid type: \".concat(t,\", allowed values 'cloud', 'raw-tracks', or 'local'\"));this.sendMessageToCallMachine(fs({action:\"local-recording-start\"},e))}},{key:\"updateRecording\",value:function(e){var t=e.layout,n=void 0===t?{preset:\"default\"}:t,r=e.instanceId;this.sendMessageToCallMachine({action:\"daily-method-update-recording\",layout:n,instanceId:r})}},{key:\"stopRecording\",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.sendMessageToCallMachine(fs({action:\"local-recording-stop\"},e))}},{key:\"startLiveStreaming\",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.sendMessageToCallMachine(fs({action:\"daily-method-start-live-streaming\"},e))}},{key:\"updateLiveStreaming\",value:function(e){var t=e.layout,n=void 0===t?{preset:\"default\"}:t,r=e.instanceId;this.sendMessageToCallMachine({action:\"daily-method-update-live-streaming\",layout:n,instanceId:r})}},{key:\"addLiveStreamingEndpoints\",value:function(e){var t=e.endpoints,n=e.instanceId;this.sendMessageToCallMachine({action:zo,endpointsOp:Xo,endpoints:t,instanceId:n})}},{key:\"removeLiveStreamingEndpoints\",value:function(e){var t=e.endpoints,n=e.instanceId;this.sendMessageToCallMachine({action:zo,endpointsOp:Zo,endpoints:t,instanceId:n})}},{key:\"stopLiveStreaming\",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.sendMessageToCallMachine(fs({action:\"daily-method-stop-live-streaming\"},e))}},{key:\"validateDailyConfig\",value:function(e){e.camSimulcastEncodings&&(console.warn(\"camSimulcastEncodings is deprecated. Use sendSettings, found in DailyCallOptions, to provide camera simulcast settings.\"),this.validateSimulcastEncodings(e.camSimulcastEncodings)),e.screenSimulcastEncodings&&console.warn(\"screenSimulcastEncodings is deprecated. Use sendSettings, found in DailyCallOptions, to provide screen simulcast settings.\"),ua()&&e.noAutoDefaultDeviceChange&&console.warn(\"noAutoDefaultDeviceChange is not supported on Android, and will be ignored.\")}},{key:\"validateSimulcastEncodings\",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(e){if(!(e instanceof Array||Array.isArray(e)))throw new Error(\"encodings must be an Array\");if(!rc(e.length,1,3))throw new Error(\"encodings must be an Array with between 1 to \".concat(3,\" layers\"));for(var r=0;r=200)throw new Error(\"Error starting dial out: displayName length must be less than 200\")}if(e.userId){if(\"string\"!=typeof e.userId)throw new Error(\"Error starting dial out: userId must be a string\");if(e.userId.length>36)throw new Error(\"Error starting dial out: userId length must be less than or equal to 36\")}return new Promise((function(n,r){t.sendMessageToCallMachine(fs({action:\"dialout-start\"},e),(function(e){e.error?r(e.error):n(e)}))}))})),function(e){return C.apply(this,arguments)})},{key:\"stopDialOut\",value:function(e){var t=this;return xs(this._callState,\"stopDialOut()\"),new Promise((function(n,r){t.sendMessageToCallMachine(fs({action:\"dialout-stop\"},e),(function(e){e.error?r(e.error):n(e)}))}))}},{key:\"sipCallTransfer\",value:(M=h((function*(e){var t=this;if(xs(this._callState,\"sipCallTransfer()\"),!e)throw new Error(\"sipCallTransfer() requires a sessionId and toEndPoint\");return e.useSipRefer=!1,tc(e,\"sipCallTransfer\"),new Promise((function(n,r){t.sendMessageToCallMachine(fs({action:ea},e),(function(e){e.error?r(e.error):n(e)}))}))})),function(e){return M.apply(this,arguments)})},{key:\"sipRefer\",value:(S=h((function*(e){var t=this;if(xs(this._callState,\"sipRefer()\"),!e)throw new Error(\"sessionId and toEndPoint are mandatory parameter\");return e.useSipRefer=!0,tc(e,\"sipRefer\"),new Promise((function(n,r){t.sendMessageToCallMachine(fs({action:ea},e),(function(e){e.error?r(e.error):n(e)}))}))})),function(e){return S.apply(this,arguments)})},{key:\"sendDTMF\",value:(k=h((function*(e){var t=this;return xs(this._callState,\"sendDTMF()\"),function(e){var t=e.sessionId,n=e.tones;if(!t||!n)throw new Error(\"sessionId and tones are mandatory parameter\");if(\"string\"!=typeof t||\"string\"!=typeof n)throw new Error(\"sessionId and tones should be of string type\");if(n.length>20)throw new Error(\"tones string must be upto 20 characters\");var r=/[^0-9A-D*#]/g,i=n.match(r);if(i&&i[0])throw new Error(\"\".concat(i[0],\" is not valid DTMF tone\"))}(e),new Promise((function(n,r){t.sendMessageToCallMachine(fs({action:\"send-dtmf\"},e),(function(e){e.error?r(e.error):n(e)}))}))})),function(e){return k.apply(this,arguments)})},{key:\"getNetworkStats\",value:function(){var e=this;if(this._callState!==ri){return{stats:{latest:{}}}}return new Promise((function(t){e.sendMessageToCallMachine({action:\"get-calc-stats\"},(function(n){t(fs({stats:n.stats},e._network))}))}))}},{key:\"testWebsocketConnectivity\",value:(w=h((function*(){var e=this;if(Fs(this._testCallInProgress,\"testWebsocketConnectivity()\"),this.needsLoad())try{yield this.load()}catch(e){return Promise.reject(e)}return new Promise((function(t,n){e.sendMessageToCallMachine({action:\"test-websocket-connectivity\"},(function(e){e.error?n(e.error):t(e.results)}))}))})),function(){return w.apply(this,arguments)})},{key:\"abortTestWebsocketConnectivity\",value:function(){this.sendMessageToCallMachine({action:\"abort-test-websocket-connectivity\"})}},{key:\"_validateVideoTrackForNetworkTests\",value:function(e){return e?e instanceof MediaStreamTrack?!!us(e,{isLocalScreenVideo:!1})||(console.error(\"Video track is not playable. This test needs a live video track.\"),!1):(console.error(\"Video track needs to be of type `MediaStreamTrack`.\"),!1):(console.error(\"Missing video track. You must provide a video track in order to run this test.\"),!1)}},{key:\"testCallQuality\",value:(b=h((function*(){var t=this;Us(),Rs(this._callObjectMode,\"testCallQuality()\"),Ns(this._callMachineInitialized,\"testCallQuality()\",null,!0),Ds(this._callState,this._isPreparingToJoin,\"testCallQuality()\");var n=this._testCallAlreadyInProgress,r=function(e){n||(t._testCallInProgress=e)};if(r(!0),this.needsLoad())try{var i=this._callState;yield this.load(),this._callState=i}catch(e){return r(!1),Promise.reject(e)}return new Promise((function(n){t.sendMessageToCallMachine({action:\"test-call-quality\",dailyJsVersion:t.properties.dailyJsVersion},(function(i){var o=i.results,a=o.result,s=e(o,ds);if(\"failed\"===a){var c,l=fs({},s);null!==(c=s.error)&&void 0!==c&&c.details?(s.error.details=JSON.parse(s.error.details),l.error=fs(fs({},l.error),{},{details:fs({},l.error.details)}),l.error.details.duringTest=\"testCallQuality\"):(l.error=l.error?fs({},l.error):{},l.error.details={duringTest:\"testCallQuality\"}),t._maybeSendToSentry(l)}r(!1),n(fs({result:a},s))}))}))})),function(){return b.apply(this,arguments)})},{key:\"stopTestCallQuality\",value:function(){this.sendMessageToCallMachine({action:\"stop-test-call-quality\"})}},{key:\"testConnectionQuality\",value:(_=h((function*(e){var t;na()?(console.warn(\"testConnectionQuality() is deprecated: use testPeerToPeerCallQuality() instead\"),t=yield this.testPeerToPeerCallQuality(e)):(console.warn(\"testConnectionQuality() is deprecated: use testCallQuality() instead\"),t=yield this.testCallQuality());var n={result:t.result,secondsElapsed:t.secondsElapsed};return t.data&&(n.data={maxRTT:t.data.maxRoundTripTime,packetLoss:t.data.avgRecvPacketLoss}),n})),function(e){return _.apply(this,arguments)})},{key:\"testPeerToPeerCallQuality\",value:(y=h((function*(e){var t=this;if(Fs(this._testCallInProgress,\"testPeerToPeerCallQuality()\"),this.needsLoad())try{yield this.load()}catch(e){return Promise.reject(e)}var n=e.videoTrack,r=e.duration;if(!this._validateVideoTrackForNetworkTests(n))throw new Error(\"Video track error\");return this._sharedTracks.videoTrackForConnectionQualityTest=n,new Promise((function(e,n){t.sendMessageToCallMachine({action:\"test-p2p-call-quality\",duration:r},(function(t){t.error?n(t.error):e(t.results)}))}))})),function(e){return y.apply(this,arguments)})},{key:\"stopTestConnectionQuality\",value:function(){na()?(console.warn(\"stopTestConnectionQuality() is deprecated: use testPeerToPeerCallQuality() and stopTestPeerToPeerCallQuality() instead\"),this.stopTestPeerToPeerCallQuality()):(console.warn(\"stopTestConnectionQuality() is deprecated: use testCallQuality() and stopTestCallQuality() instead\"),this.stopTestCallQuality())}},{key:\"stopTestPeerToPeerCallQuality\",value:function(){this.sendMessageToCallMachine({action:\"stop-test-p2p-call-quality\"})}},{key:\"testNetworkConnectivity\",value:(g=h((function*(e){var t=this;if(Fs(this._testCallInProgress,\"testNetworkConnectivity()\"),this.needsLoad())try{yield this.load()}catch(e){return Promise.reject(e)}if(!this._validateVideoTrackForNetworkTests(e))throw new Error(\"Video track error\");return this._sharedTracks.videoTrackForNetworkConnectivityTest=e,new Promise((function(e,n){t.sendMessageToCallMachine({action:\"test-network-connectivity\"},(function(t){t.error?n(t.error):e(t.results)}))}))})),function(e){return g.apply(this,arguments)})},{key:\"abortTestNetworkConnectivity\",value:function(){this.sendMessageToCallMachine({action:\"abort-test-network-connectivity\"})}},{key:\"getCpuLoadStats\",value:function(){var e=this;return new Promise((function(t){if(e._callState===ri){e.sendMessageToCallMachine({action:\"get-cpu-load-stats\"},(function(e){t(e.cpuStats)}))}else t({cpuLoadState:void 0,cpuLoadStateReason:void 0,stats:{}})}))}},{key:\"_validateEncodingLayerHasValidProperties\",value:function(e){var t;if(!((null===(t=Object.keys(e))||void 0===t?void 0:t.length)>0))throw new Error(\"Empty encoding is not allowed. At least one of these valid keys should be specified:\"+Object.values(Ms))}},{key:\"_validateVideoSendSettings\",value:function(e,t){var r=\"screenVideo\"===e?[\"default-screen-video\",\"detail-optimized\",\"motion-optimized\",\"motion-and-detail-balanced\"]:[\"default-video\",\"bandwidth-optimized\",\"bandwidth-and-quality-balanced\",\"quality-optimized\",\"adaptive-2-layers\",\"adaptive-3-layers\"],i=\"Video send settings should be either an object or one of the supported presets: \".concat(r.join());if(\"string\"==typeof t){if(!r.includes(t))throw new Error(i)}else{if(\"object\"!==n(t))throw new Error(i);if(!t.maxQuality&&!t.encodings&&void 0===t.allowAdaptiveLayers)throw new Error(\"Video send settings must contain at least maxQuality, allowAdaptiveLayers or encodings attribute\");if(t.maxQuality&&-1===[\"low\",\"medium\",\"high\"].indexOf(t.maxQuality))throw new Error(\"maxQuality must be either low, medium or high\");if(t.encodings){var o=!1;switch(Object.keys(t.encodings).length){case 1:o=!t.encodings.low;break;case 2:o=!t.encodings.low||!t.encodings.medium;break;case 3:o=!t.encodings.low||!t.encodings.medium||!t.encodings.high;break;default:o=!0}if(o)throw new Error(\"Encodings must be defined as: low, low and medium, or low, medium and high.\");t.encodings.low&&this._validateEncodingLayerHasValidProperties(t.encodings.low),t.encodings.medium&&this._validateEncodingLayerHasValidProperties(t.encodings.medium),t.encodings.high&&this._validateEncodingLayerHasValidProperties(t.encodings.high)}}}},{key:\"validateUpdateSendSettings\",value:function(e){var t=this;if(!e||0===Object.keys(e).length)throw new Error(\"Send settings must contain at least information for one track!\");Object.entries(e).forEach((function(e){var n=v(e,2),r=n[0],i=n[1];t._validateVideoSendSettings(r,i)}))}},{key:\"updateSendSettings\",value:function(e){var t=this;return this.validateUpdateSendSettings(e),this.needsLoad()?(this._preloadCache.sendSettings=e,{sendSettings:this._preloadCache.sendSettings}):new Promise((function(n,r){t.sendMessageToCallMachine({action:\"update-send-settings\",sendSettings:e},(function(e){e.error?r(e.error):n(e.sendSettings)}))}))}},{key:\"getSendSettings\",value:function(){return this._sendSettings||this._preloadCache.sendSettings}},{key:\"getLocalAudioLevel\",value:function(){return this._localAudioLevel}},{key:\"getRemoteParticipantsAudioLevel\",value:function(){return this._remoteParticipantsAudioLevel}},{key:\"getActiveSpeaker\",value:function(){return Us(),this._activeSpeaker}},{key:\"setActiveSpeakerMode\",value:function(e){return Us(),this.sendMessageToCallMachine({action:\"set-active-speaker-mode\",enabled:e}),this}},{key:\"activeSpeakerMode\",value:function(){return Us(),this._activeSpeakerMode}},{key:\"subscribeToTracksAutomatically\",value:function(){return this._preloadCache.subscribeToTracksAutomatically}},{key:\"setSubscribeToTracksAutomatically\",value:function(e){return xs(this._callState,\"setSubscribeToTracksAutomatically()\",\"Use the subscribeToTracksAutomatically configuration property.\"),this._preloadCache.subscribeToTracksAutomatically=e,this.sendMessageToCallMachine({action:\"daily-method-subscribe-to-tracks-automatically\",enabled:e}),this}},{key:\"enumerateDevices\",value:(f=h((function*(){var e=this;if(this._callObjectMode){var t=yield navigator.mediaDevices.enumerateDevices();return\"Firefox\"===pa()&&ha().major>115&&ha().major<123&&(t=t.filter((function(e){return\"audiooutput\"!==e.kind}))),{devices:t.map((function(e){var t=JSON.parse(JSON.stringify(e));if(!na()&&\"videoinput\"===e.kind&&e.getCapabilities){var n,r=e.getCapabilities();t.facing=(null==r||null===(n=r.facingMode)||void 0===n?void 0:n.length)>=1?r.facingMode[0]:void 0}return t}))}}return new Promise((function(t){e.sendMessageToCallMachine({action:\"enumerate-devices\"},(function(e){t({devices:e.devices})}))}))})),function(){return f.apply(this,arguments)})},{key:\"sendAppMessage\",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"*\";if(xs(this._callState,\"sendAppMessage()\"),JSON.stringify(e).length>this._maxAppMessageSize)throw new Error(\"Message data too large. Max size is \"+this._maxAppMessageSize);return this.sendMessageToCallMachine({action:\"app-msg\",data:e,to:t}),this}},{key:\"addFakeParticipant\",value:function(e){return Us(),xs(this._callState,\"addFakeParticipant()\"),this.sendMessageToCallMachine(fs({action:\"add-fake-participant\"},e)),this}},{key:\"setShowNamesMode\",value:function(e){return Bs(this._callObjectMode,\"setShowNamesMode()\"),Us(),e&&\"always\"!==e&&\"never\"!==e?(console.error('setShowNamesMode argument should be \"always\", \"never\", or false'),this):(this.sendMessageToCallMachine({action:\"set-show-names\",mode:e}),this)}},{key:\"setShowLocalVideo\",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Bs(this._callObjectMode,\"setShowLocalVideo()\"),Us(),xs(this._callState,\"setShowLocalVideo()\"),\"boolean\"!=typeof e?(console.error(\"setShowLocalVideo only accepts a boolean value\"),this):(this.sendMessageToCallMachine({action:\"set-show-local-video\",show:e}),this._showLocalVideo=e,this)}},{key:\"showLocalVideo\",value:function(){return Bs(this._callObjectMode,\"showLocalVideo()\"),Us(),this._showLocalVideo}},{key:\"setShowParticipantsBar\",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Bs(this._callObjectMode,\"setShowParticipantsBar()\"),Us(),xs(this._callState,\"setShowParticipantsBar()\"),\"boolean\"!=typeof e?(console.error(\"setShowParticipantsBar only accepts a boolean value\"),this):(this.sendMessageToCallMachine({action:\"set-show-participants-bar\",show:e}),this._showParticipantsBar=e,this)}},{key:\"showParticipantsBar\",value:function(){return Bs(this._callObjectMode,\"showParticipantsBar()\"),Us(),this._showParticipantsBar}},{key:\"customIntegrations\",value:function(){return Us(),Bs(this._callObjectMode,\"customIntegrations()\"),this._customIntegrations}},{key:\"setCustomIntegrations\",value:function(e){return Us(),Bs(this._callObjectMode,\"setCustomIntegrations()\"),xs(this._callState,\"setCustomIntegrations()\"),Zs(e)?(this.sendMessageToCallMachine({action:\"set-custom-integrations\",integrations:e}),this._customIntegrations=e,this):this}},{key:\"startCustomIntegrations\",value:function(e){var t=this;if(Us(),Bs(this._callObjectMode,\"startCustomIntegrations()\"),xs(this._callState,\"startCustomIntegrations()\"),Array.isArray(e)&&e.some((function(e){return\"string\"!=typeof e}))||!Array.isArray(e)&&\"string\"!=typeof e)return console.error(\"startCustomIntegrations() only accepts string | string[]\"),this;var n=\"string\"==typeof e?[e]:e,r=n.filter((function(e){return!(e in t._customIntegrations)}));return r.length?(console.error(\"Can't find custom integration(s): \\\"\".concat(r.join(\", \"),'\"')),this):(this.sendMessageToCallMachine({action:\"start-custom-integrations\",ids:n}),this)}},{key:\"stopCustomIntegrations\",value:function(e){var t=this;if(Us(),Bs(this._callObjectMode,\"stopCustomIntegrations()\"),xs(this._callState,\"stopCustomIntegrations()\"),Array.isArray(e)&&e.some((function(e){return\"string\"!=typeof e}))||!Array.isArray(e)&&\"string\"!=typeof e)return console.error(\"stopCustomIntegrations() only accepts string | string[]\"),this;var n=\"string\"==typeof e?[e]:e,r=n.filter((function(e){return!(e in t._customIntegrations)}));return r.length?(console.error(\"Can't find custom integration(s): \\\"\".concat(r.join(\", \"),'\"')),this):(this.sendMessageToCallMachine({action:\"stop-custom-integrations\",ids:n}),this)}},{key:\"customTrayButtons\",value:function(){return Bs(this._callObjectMode,\"customTrayButtons()\"),Us(),this._customTrayButtons}},{key:\"updateCustomTrayButtons\",value:function(e){return Bs(this._callObjectMode,\"updateCustomTrayButtons()\"),Us(),xs(this._callState,\"updateCustomTrayButtons()\"),Xs(e)?(this.sendMessageToCallMachine({action:\"update-custom-tray-buttons\",btns:e}),this._customTrayButtons=e,this):(console.error(\"updateCustomTrayButtons only accepts a dictionary of the type \".concat(JSON.stringify(Ts))),this)}},{key:\"theme\",value:function(){return Bs(this._callObjectMode,\"theme()\"),this.properties.theme}},{key:\"setTheme\",value:function(e){var t=this;return Bs(this._callObjectMode,\"setTheme()\"),new Promise((function(n,r){try{t.validateProperties({theme:e}),t.properties.theme=fs({},e),t.sendMessageToCallMachine({action:\"set-theme\",theme:t.properties.theme});try{t.emitDailyJSEvent({action:Ri,theme:t.properties.theme})}catch(e){console.log(\"could not emit 'theme-updated'\",e)}n(t.properties.theme)}catch(e){r(e)}}))}},{key:\"requestFullscreen\",value:(p=h((function*(){if(Us(),this._iframe&&!document.fullscreenElement&&oa())try{(yield this._iframe.requestFullscreen)?this._iframe.requestFullscreen():this._iframe.webkitRequestFullscreen()}catch(e){console.log(\"could not make video call fullscreen\",e)}})),function(){return p.apply(this,arguments)})},{key:\"exitFullscreen\",value:function(){Us(),document.fullscreenElement?document.exitFullscreen():document.webkitFullscreenElement&&document.webkitExitFullscreen()}},{key:\"getSidebarView\",value:(u=h((function*(){var e=this;return this._callObjectMode?(console.error(\"getSidebarView is not available in callObject mode\"),Promise.resolve(null)):new Promise((function(t){e.sendMessageToCallMachine({action:\"get-sidebar-view\"},(function(e){t(e.view)}))}))})),function(){return u.apply(this,arguments)})},{key:\"setSidebarView\",value:function(e){return this._callObjectMode?(console.error(\"setSidebarView is not available in callObject mode\"),this):(this.sendMessageToCallMachine({action:\"set-sidebar-view\",view:e}),this)}},{key:\"room\",value:(l=h((function*(){var e=this,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).includeRoomConfigDefaults,n=void 0===t||t;return this._accessState.access===pi||this.needsLoad()?this.properties.url?{roomUrlPendingJoin:this.properties.url}:null:new Promise((function(t){e.sendMessageToCallMachine({action:\"lib-room-info\",includeRoomConfigDefaults:n},(function(e){delete e.action,delete e.callbackStamp,t(e)}))}))})),function(){return l.apply(this,arguments)})},{key:\"geo\",value:(s=h((function*(){try{var e=yield fetch(\"https://gs.daily.co/_ks_/x-swsl/:\");return{current:(yield e.json()).geo}}catch(e){return console.error(\"geo lookup failed\",e),{current:\"\"}}})),function(){return s.apply(this,arguments)})},{key:\"setNetworkTopology\",value:(i=h((function*(e){var t=this;return Us(),xs(this._callState,\"setNetworkTopology()\"),new Promise((function(n,r){t.sendMessageToCallMachine({action:\"set-network-topology\",opts:e},(function(e){e.error?r({error:e.error}):n({workerId:e.workerId})}))}))})),function(e){return i.apply(this,arguments)})},{key:\"getNetworkTopology\",value:(r=h((function*(){var e=this;return new Promise((function(t,n){e.needsLoad()&&t({topology:\"none\"}),e.sendMessageToCallMachine({action:\"get-network-topology\"},(function(e){e.error?n({error:e.error}):t({topology:e.topology})}))}))})),function(){return r.apply(this,arguments)})},{key:\"setPlayNewParticipantSound\",value:function(e){if(Us(),\"number\"!=typeof e&&!0!==e&&!1!==e)throw new Error(\"argument to setShouldPlayNewParticipantSound should be true, false, or a number, but is \".concat(e));this.sendMessageToCallMachine({action:\"daily-method-set-play-ding\",arg:e})}},{key:\"on\",value:function(e,t){return m.prototype.on.call(this,e,t)}},{key:\"once\",value:function(e,t){return m.prototype.once.call(this,e,t)}},{key:\"off\",value:function(e,t){return m.prototype.off.call(this,e,t)}},{key:\"validateProperties\",value:function(e){var t,n;if(null!=e&&null!==(t=e.dailyConfig)&&void 0!==t&&t.userMediaAudioConstraints){var r,i,o;na()||console.warn(\"userMediaAudioConstraints is deprecated. You can override constraints with inputSettings.audio.settings, found in DailyCallOptions.\");var a=e.inputSettings||{};a.audio=(null===(r=e.inputSettings)||void 0===r?void 0:r.audio)||{},a.audio.settings=(null===(i=e.inputSettings)||void 0===i||null===(o=i.audio)||void 0===o?void 0:o.settings)||{},a.audio.settings=fs(fs({},a.audio.settings),e.dailyConfig.userMediaAudioConstraints),e.inputSettings=a,delete e.dailyConfig.userMediaAudioConstraints}if(null!=e&&null!==(n=e.dailyConfig)&&void 0!==n&&n.userMediaVideoConstraints){var s,c,l;na()||console.warn(\"userMediaVideoConstraints is deprecated. You can override constraints with inputSettings.video.settings, found in DailyCallOptions.\");var u=e.inputSettings||{};u.video=(null===(s=e.inputSettings)||void 0===s?void 0:s.video)||{},u.video.settings=(null===(c=e.inputSettings)||void 0===c||null===(l=c.video)||void 0===l?void 0:l.settings)||{},u.video.settings=fs(fs({},u.video.settings),e.dailyConfig.userMediaVideoConstraints),e.inputSettings=u,delete e.dailyConfig.userMediaVideoConstraints}for(var d in e){if(!Os[d])throw new Error(\"unrecognized property '\".concat(d,\"'\"));if(Os[d].validate&&!Os[d].validate(e[d],this))throw new Error(\"property '\".concat(d,\"': \").concat(Os[d].help))}}},{key:\"assembleMeetingUrl\",value:function(){var e,t,n=fs(fs({},this.properties),{},{emb:this.callClientId,embHref:encodeURIComponent(window.location.href),proxy:null!==(e=this.properties.dailyConfig)&&void 0!==e&&e.proxyUrl?encodeURIComponent(null===(t=this.properties.dailyConfig)||void 0===t?void 0:t.proxyUrl):void 0}),r=n.url.match(/\\?/)?\"&\":\"?\";return n.url+r+Object.keys(Os).filter((function(e){return Os[e].queryString&&void 0!==n[e]})).map((function(e){return\"\".concat(Os[e].queryString,\"=\").concat(n[e])})).join(\"&\")}},{key:\"needsLoad\",value:function(){return[Zr,ei,ii,oi].includes(this._callState)}},{key:\"sendMessageToCallMachine\",value:function(e,t){if(this._destroyed&&(this._logUseAfterDestroy(),this.strictMode))throw new Error(\"Use after destroy\");this._messageChannel.sendMessageToCallMachine(e,t,this.callClientId,this._iframe)}},{key:\"forwardPackagedMessageToCallMachine\",value:function(e){this._messageChannel.forwardPackagedMessageToCallMachine(e,this._iframe,this.callClientId)}},{key:\"addListenerForPackagedMessagesFromCallMachine\",value:function(e){return this._messageChannel.addListenerForPackagedMessagesFromCallMachine(e,this.callClientId)}},{key:\"removeListenerForPackagedMessagesFromCallMachine\",value:function(e){this._messageChannel.removeListenerForPackagedMessagesFromCallMachine(e)}},{key:\"handleMessageFromCallMachine\",value:function(t){switch(t.action){case Ni:this.sendMessageToCallMachine(fs({action:Fi},this.properties));break;case\"call-machine-initialized\":this._callMachineInitialized=!0;var n={action:Wo,level:\"log\",code:1011,stats:{event:\"bundle load\",time:\"no-op\"===this._bundleLoadTime?0:this._bundleLoadTime,preLoaded:\"no-op\"===this._bundleLoadTime,url:X(this.properties.dailyConfig)}};this.sendMessageToCallMachine(n),this._delayDuplicateInstanceLog&&this._logDuplicateInstanceAttempt();break;case Vi:this._loadedCallback&&(this._loadedCallback(),this._loadedCallback=null),this.emitDailyJSEvent(t);break;case zi:var r,i=fs({},t);delete i.internal,this._maxAppMessageSize=(null===(r=t.internal)||void 0===r?void 0:r._maxAppMessageSize)||Vo,this._joinedCallback&&(this._joinedCallback(t.participants),this._joinedCallback=null),this.emitDailyJSEvent(i);break;case Hi:case Gi:if(this._callState===ii)return;if(t.participant&&t.participant.session_id){var o=t.participant.local?\"local\":t.participant.session_id;if(this._callObjectMode){var a=this._callMachine().store;Ga(t.participant,a),Qa(t.participant,a),Ka(t.participant,this._participants[o],a)}try{this.maybeParticipantTracksStopped(this._participants[o],t.participant),this.maybeParticipantTracksStarted(this._participants[o],t.participant),this.maybeEventRecordingStopped(this._participants[o],t.participant),this.maybeEventRecordingStarted(this._participants[o],t.participant)}catch(e){console.error(\"track events error\",e)}this.compareEqualForParticipantUpdateEvent(t.participant,this._participants[o])||(this._participants[o]=fs({},t.participant),this.toggleParticipantAudioBasedOnNativeAudioFocus(),this.emitDailyJSEvent(t))}break;case Qi:if(t.participant&&t.participant.session_id){var s=this._participants[t.participant.session_id];s&&this.maybeParticipantTracksStopped(s,null),delete this._participants[t.participant.session_id],this.emitDailyJSEvent(t)}break;case Yi:D(this._participantCounts,t.participantCounts)||(this._participantCounts=t.participantCounts,this.emitDailyJSEvent(t));break;case Ki:var c={access:t.access};t.awaitingAccess&&(c.awaitingAccess=t.awaitingAccess),D(this._accessState,c)||(this._accessState=c,this.emitDailyJSEvent(t));break;case Xi:if(t.meetingSession){this._meetingSessionSummary=t.meetingSession,this.emitDailyJSEvent(t);var l=fs(fs({},t),{},{action:\"meeting-session-updated\"});this.emitDailyJSEvent(l)}break;case Uo:var u;this._iframe&&!t.preserveIframe&&(this._iframe.src=\"\"),this._updateCallState(oi),this.resetMeetingDependentVars(),this._loadedCallback&&(this._loadedCallback(t.errorMsg),this._loadedCallback=null),t.preserveIframe;var d=e(t,ps);null!=d&&null!==(u=d.error)&&void 0!==u&&u.details&&(d.error.details=JSON.parse(d.error.details)),this._maybeSendToSentry(t),this._joinedCallback&&(this._joinedCallback(null,d),this._joinedCallback=null),this.emitDailyJSEvent(d);break;case Wi:this._callState!==oi&&this._updateCallState(ii),this.resetMeetingDependentVars(),this._resolveLeave&&(this._resolveLeave(),this._resolveLeave=null),this.emitDailyJSEvent(t);break;case\"selected-devices-updated\":t.devices&&this.emitDailyJSEvent(t);break;case Eo:var p=t.threshold,h=t.quality;p===this._network.threshold&&h===this._network.quality||(this._network.quality=h,this._network.threshold=p,this.emitDailyJSEvent(t));break;case Po:t&&t.cpuLoadState&&this.emitDailyJSEvent(t);break;case Oo:t&&void 0!==t.faceCounts&&this.emitDailyJSEvent(t);break;case Mo:var f=t.activeSpeaker;this._activeSpeaker.peerId!==f.peerId&&(this._activeSpeaker.peerId=f.peerId,this.emitDailyJSEvent({action:t.action,activeSpeaker:this._activeSpeaker}));break;case\"show-local-video-changed\":if(this._callObjectMode)return;var v=t.show;this._showLocalVideo=v,this.emitDailyJSEvent({action:t.action,show:v});break;case Co:var g=t.enabled;this._activeSpeakerMode!==g&&(this._activeSpeakerMode=g,this.emitDailyJSEvent({action:t.action,enabled:this._activeSpeakerMode}));break;case to:case no:case ro:this._waitingParticipants=t.allWaitingParticipants,this.emitDailyJSEvent({action:t.action,participant:t.participant});break;case Fo:D(this._receiveSettings,t.receiveSettings)||(this._receiveSettings=t.receiveSettings,this.emitDailyJSEvent({action:t.action,receiveSettings:t.receiveSettings}));break;case Ro:this._maybeUpdateInputSettings(t.inputSettings);break;case\"send-settings-updated\":D(this._sendSettings,t.sendSettings)||(this._sendSettings=t.sendSettings,this._preloadCache.sendSettings=null,this.emitDailyJSEvent({action:t.action,sendSettings:t.sendSettings}));break;case\"local-audio-level\":this._localAudioLevel=t.audioLevel,this._preloadCache.localAudioLevelObserver=null,this.emitDailyJSEvent(t);break;case\"remote-participants-audio-level\":this._remoteParticipantsAudioLevel=t.participantsAudioLevel,this._preloadCache.remoteParticipantsAudioLevelObserver=null,this.emitDailyJSEvent(t);break;case yo:var m=t.session_id;this._rmpPlayerState[m]=t.playerState,this.emitDailyJSEvent(t);break;case bo:delete this._rmpPlayerState[t.session_id],this.emitDailyJSEvent(t);break;case _o:var y=t.session_id,_=this._rmpPlayerState[y];_&&this.compareEqualForRMPUpdateEvent(_,t.remoteMediaPlayerState)||(this._rmpPlayerState[y]=t.remoteMediaPlayerState,this.emitDailyJSEvent(t));break;case\"custom-button-click\":case\"sidebar-view-changed\":this.emitDailyJSEvent(t);break;case Zi:var b=this._meetingSessionState.topology!==(t.meetingSessionState&&t.meetingSessionState.topology);this._meetingSessionState=ic(t.meetingSessionState,this._callObjectMode),(this._callObjectMode||b)&&this.emitDailyJSEvent(t);break;case wo:this._isScreenSharing=!0,this.emitDailyJSEvent(t);break;case ko:case So:this._isScreenSharing=!1,this.emitDailyJSEvent(t);break;case lo:case uo:case po:case ho:case fo:case ao:case so:case co:case Ji:case $i:case go:case mo:case\"test-completed\":case To:case vo:case Lo:case xo:case Io:case Do:case Bo:case No:case\"dialin-ready\":case\"dialin-connected\":case\"dialin-error\":case\"dialin-stopped\":case\"dialin-warning\":case\"dialout-connected\":case\"dialout-answered\":case\"dialout-error\":case\"dialout-stopped\":case\"dialout-warning\":this.emitDailyJSEvent(t);break;case\"request-fullscreen\":this.requestFullscreen();break;case\"request-exit-fullscreen\":this.exitFullscreen()}}},{key:\"maybeEventRecordingStopped\",value:function(e,t){var n=\"record\";e&&(t.local||!1!==t[n]||e[n]===t[n]||this.emitDailyJSEvent({action:uo}))}},{key:\"maybeEventRecordingStarted\",value:function(e,t){var n=\"record\";e&&(t.local||!0!==t[n]||e[n]===t[n]||this.emitDailyJSEvent({action:lo}))}},{key:\"_trackStatePlayable\",value:function(e){return!(!e||e.state!==di)}},{key:\"_trackChanged\",value:function(e,t){return!((null==e?void 0:e.id)===(null==t?void 0:t.id))}},{key:\"maybeEventTrackStopped\",value:function(e,t,n){var r,i,o=null!==(r=null==t?void 0:t.tracks[e])&&void 0!==r?r:null,a=null!==(i=null==n?void 0:n.tracks[e])&&void 0!==i?i:null,s=null==o?void 0:o.track;if(s){var c=this._trackStatePlayable(o),l=this._trackStatePlayable(a),u=this._trackChanged(s,null==a?void 0:a.track);c&&(l&&!u||this.emitDailyJSEvent({action:oo,track:s,participant:null!=n?n:t,type:e}))}}},{key:\"maybeEventTrackStarted\",value:function(e,t,n){var r,i,o=null!==(r=null==t?void 0:t.tracks[e])&&void 0!==r?r:null,a=null!==(i=null==n?void 0:n.tracks[e])&&void 0!==i?i:null,s=null==a?void 0:a.track;if(s){var c=this._trackStatePlayable(o),l=this._trackStatePlayable(a),u=this._trackChanged(null==o?void 0:o.track,s);l&&(c&&!u||this.emitDailyJSEvent({action:io,track:s,participant:n,type:e}))}}},{key:\"maybeParticipantTracksStopped\",value:function(e,t){if(e)for(var n in e.tracks)this.maybeEventTrackStopped(n,e,t)}},{key:\"maybeParticipantTracksStarted\",value:function(e,t){if(t)for(var n in t.tracks)this.maybeEventTrackStarted(n,e,t)}},{key:\"compareEqualForRMPUpdateEvent\",value:function(e,t){var n,r;return e.state===t.state&&(null===(n=e.settings)||void 0===n?void 0:n.volume)===(null===(r=t.settings)||void 0===r?void 0:r.volume)}},{key:\"emitDailyJSEvent\",value:function(e){try{e.callClientId=this.callClientId,this.emit(e.action,e)}catch(t){console.log(\"could not emit\",e,t)}}},{key:\"compareEqualForParticipantUpdateEvent\",value:function(e,t){return!!D(e,t)&&((!e.videoTrack||!t.videoTrack||e.videoTrack.id===t.videoTrack.id&&e.videoTrack.muted===t.videoTrack.muted&&e.videoTrack.enabled===t.videoTrack.enabled)&&(!e.audioTrack||!t.audioTrack||e.audioTrack.id===t.audioTrack.id&&e.audioTrack.muted===t.audioTrack.muted&&e.audioTrack.enabled===t.audioTrack.enabled))}},{key:\"nativeUtils\",value:function(){return na()?\"undefined\"==typeof DailyNativeUtils?(console.warn(\"in React Native, DailyNativeUtils is expected to be available\"),null):DailyNativeUtils:null}},{key:\"updateIsPreparingToJoin\",value:function(e){this._updateCallState(this._callState,e)}},{key:\"_updateCallState\",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this._isPreparingToJoin;if(e!==this._callState||t!==this._isPreparingToJoin){var n=this._callState,r=this._isPreparingToJoin;this._callState=e,this._isPreparingToJoin=t;var i=this._callState===ri;this.updateShowAndroidOngoingMeetingNotification(i);var o=Is(n,r),a=Is(this._callState,this._isPreparingToJoin);o!==a&&(this.updateKeepDeviceAwake(a),this.updateDeviceAudioMode(a),this.updateNoOpRecordingEnsuringBackgroundContinuity(a))}}},{key:\"resetMeetingDependentVars\",value:function(){this._participants={},this._participantCounts=ks,this._waitingParticipants={},this._activeSpeaker={},this._activeSpeakerMode=!1,this._didPreAuth=!1,this._accessState={access:pi},this._finalSummaryOfPrevSession=this._meetingSessionSummary,this._meetingSessionSummary={},this._meetingSessionState=ic(ws,this._callObjectMode),this._isScreenSharing=!1,this._receiveSettings={},this._inputSettings=void 0,this._sendSettings={},this._localAudioLevel=0,this._isLocalAudioLevelObserverRunning=!1,this._remoteParticipantsAudioLevel={},this._isRemoteParticipantsAudioLevelObserverRunning=!1,this._maxAppMessageSize=Vo,this._callMachineInitialized=!1,this._bundleLoadTime=void 0,this._preloadCache}},{key:\"updateKeepDeviceAwake\",value:function(e){na()&&this.nativeUtils().setKeepDeviceAwake(e,this.callClientId)}},{key:\"updateDeviceAudioMode\",value:function(e){if(na()&&!this.disableReactNativeAutoDeviceManagement(\"audio\")){var t=e?this._nativeInCallAudioMode:\"idle\";this.nativeUtils().setAudioMode(t)}}},{key:\"updateShowAndroidOngoingMeetingNotification\",value:function(e){if(na()&&this.nativeUtils().setShowOngoingMeetingNotification){var t,n,r,i;if(this.properties.reactNativeConfig&&this.properties.reactNativeConfig.androidInCallNotification){var o=this.properties.reactNativeConfig.androidInCallNotification;t=o.title,n=o.subtitle,r=o.iconName,i=o.disableForCustomOverride}i&&(e=!1),this.nativeUtils().setShowOngoingMeetingNotification(e,t,n,r,this.callClientId)}}},{key:\"updateNoOpRecordingEnsuringBackgroundContinuity\",value:function(e){na()&&this.nativeUtils().enableNoOpRecordingEnsuringBackgroundContinuity&&this.nativeUtils().enableNoOpRecordingEnsuringBackgroundContinuity(e)}},{key:\"toggleParticipantAudioBasedOnNativeAudioFocus\",value:function(){var e,t;if(na()){var n=null===(e=this._callMachine())||void 0===e||null===(t=e.store)||void 0===t?void 0:t.getState();for(var r in null==n?void 0:n.streams){var i=n.streams[r];i&&i.pendingTrack&&\"audio\"===i.pendingTrack.kind&&(i.pendingTrack.enabled=this._hasNativeAudioFocus)}}}},{key:\"disableReactNativeAutoDeviceManagement\",value:function(e){return this.properties.reactNativeConfig&&this.properties.reactNativeConfig.disableAutoDeviceManagement&&this.properties.reactNativeConfig.disableAutoDeviceManagement[e]}},{key:\"absoluteUrl\",value:function(e){if(void 0!==e){var t=document.createElement(\"a\");return t.href=e,t.href}}},{key:\"sayHello\",value:function(){var e=\"hello, world.\";return console.log(e),e}},{key:\"_logUseAfterDestroy\",value:function(){var e=Object.values(ys)[0];if(this.needsLoad()){if(e&&!e.needsLoad()){var t={action:Wo,level:\"error\",code:this.strictMode?9995:9997};e.sendMessageToCallMachine(t)}else if(!this.strictMode){console.error(\"You are are attempting to use a call instance that was previously destroyed, which is unsupported. Please remove `strictMode: false` from your constructor properties to enable strict mode to track down and fix this unsupported usage.\")}}else{var n={action:Wo,level:\"error\",code:this.strictMode?9995:9997};this._messageChannel.sendMessageToCallMachine(n,null,this.callClientId,this._iframe)}}},{key:\"_logDuplicateInstanceAttempt\",value:function(){for(var e=0,t=Object.values(ys);e0&&void 0!==arguments[0]?arguments[0]:{};return e.layout=\"none\",new ee(null,e)}},{key:\"wrap\",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(Us(),!e||!e.contentWindow||\"string\"!=typeof e.src)throw new Error(\"DailyIframe::Wrap needs an iframe-like first argument\");return t.layout||(t.customLayout?t.layout=\"custom-v1\":t.layout=\"browser\"),new ee(e,t)}},{key:\"createFrame\",value:function(e,t){var n,r;Us(),e&&t?(n=e,r=t):e&&e.append?(n=e,r={}):(n=document.body,r=e||{});var i=r.iframeStyle;i||(i=n===document.body?{position:\"fixed\",border:\"1px solid black\",backgroundColor:\"white\",width:\"375px\",height:\"450px\",right:\"1em\",bottom:\"1em\"}:{border:0,width:\"100%\",height:\"100%\"});var o=document.createElement(\"iframe\");window.navigator&&window.navigator.userAgent.match(/Chrome\\/61\\./)?o.allow=\"microphone, camera\":o.allow=\"microphone; camera; autoplay; display-capture; screen-wake-lock\",o.style.visibility=\"hidden\",n.appendChild(o),o.style.visibility=null,Object.keys(i).forEach((function(e){return o.style[e]=i[e]})),r.layout||(r.customLayout?r.layout=\"custom-v1\":r.layout=\"browser\");try{return new ee(o,r)}catch(e){throw n.removeChild(o),e}}},{key:\"createTransparentFrame\",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Us();var t=document.createElement(\"iframe\");return t.allow=\"microphone; camera; autoplay\",t.style.cssText=\"\\n position: fixed;\\n top: 0;\\n left: 0;\\n width: 100%;\\n height: 100%;\\n border: 0;\\n pointer-events: none;\\n \",document.body.appendChild(t),e.layout||(e.layout=\"custom-v1\"),ee.wrap(t,e)}},{key:\"getCallInstance\",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0;return e?ys[e]:Object.values(ys)[0]}}]),ee}();function Ls(e,t){var n={};for(var r in e)if(e[r]instanceof MediaStreamTrack)console.warn(\"MediaStreamTrack found in props or cache.\",r),n[r]=Ho;else if(\"dailyConfig\"===r){if(e[r].modifyLocalSdpHook){var i=window._daily.instances[t].customCallbacks||{};i.modifyLocalSdpHook=e[r].modifyLocalSdpHook,window._daily.instances[t].customCallbacks=i,delete e[r].modifyLocalSdpHook}if(e[r].modifyRemoteSdpHook){var o=window._daily.instances[t].customCallbacks||{};o.modifyRemoteSdpHook=e[r].modifyRemoteSdpHook,window._daily.instances[t].customCallbacks=o,delete e[r].modifyRemoteSdpHook}n[r]=e[r]}else n[r]=e[r];return n}function xs(e){var t=arguments.length>2?arguments[2]:void 0;if(e!==ri){var n=\"\".concat(arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"This daily-js method\",\" only supported after join.\");throw t&&(n+=\" \".concat(t)),console.error(n),new Error(n)}}function Is(e,t){return[ni,ri].includes(e)||t}function Ds(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:\"This daily-js method\",r=arguments.length>3?arguments[3]:void 0;if(Is(e,t)){var i=\"\".concat(n,\" not supported after joining a meeting.\");throw r&&(i+=\" \".concat(r)),console.error(i),new Error(i)}}function Ns(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"This daily-js method\",n=arguments.length>2?arguments[2]:void 0;if(!e){var r=\"\".concat(t,arguments.length>3&&void 0!==arguments[3]&&arguments[3]?\" requires preAuth() or startCamera() to initialize call state.\":\" requires preAuth(), startCamera(), or join() to initialize call state.\");throw n&&(r+=\" \".concat(n)),console.error(r),new Error(r)}}function Fs(e){if(e){var t=\"A pre-call quality test is in progress. Please try \".concat(arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"This daily-js method\",\" again once testing has completed. Use stopTestCallQuality() to end it early.\");throw console.error(t),new Error(t)}}function Rs(e){if(!e){var t=\"\".concat(arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"This daily-js method\",\" is only supported on custom callObject instances\");throw console.error(t),new Error(t)}}function Bs(e){if(e){var t=\"\".concat(arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"This daily-js method\",\" is only supported as part of Daily's Prebuilt\");throw console.error(t),new Error(t)}}function Us(){if(na())throw new Error(\"This daily-js method is not currently supported in React Native\")}function Vs(){if(!na())throw new Error(\"This daily-js method is only supported in React Native\")}function Js(e){if(void 0===e)return!0;var t;if(\"string\"==typeof e)t=e;else try{t=JSON.stringify(e),D(JSON.parse(t),e)||console.warn(\"The userData provided will be modified when serialized.\")}catch(e){throw Error(\"userData must be serializable to JSON: \".concat(e))}if(t.length>4096)throw Error(\"userData is too large (\".concat(t.length,\" characters). Maximum size suppported is \").concat(4096,\".\"));return!0}function $s(e,t){for(var n=t.allowAllParticipantsKey,r=function(e){var t=[\"local\"];return n||t.push(\"*\"),e&&!t.includes(e)},i=function(e){return!!(void 0===e.layer||Number.isInteger(e.layer)&&e.layer>=0||\"inherit\"===e.layer)},o=function(e){return!!e&&(!(e.video&&!i(e.video))&&!(e.screenVideo&&!i(e.screenVideo)))},a=0,s=Object.entries(e);a0&&console.error(\"Ignoring settings for browser- or platform-unsupported input processor(s): \".concat(i.join(\", \"))),e.audio&&e.audio.settings&&(e.audio.settings.customTrack?(n.audioTrack=e.audio.settings.customTrack,e.audio.settings={customTrack:Ho}):delete n.audioTrack),e.video&&e.video.settings&&(e.video.settings.customTrack?(n.videoTrack=e.video.settings.customTrack,e.video.settings={customTrack:Ho}):delete n.videoTrack)}function Ws(e){if(na())return console.warn(\"Video processing is not yet supported in React Native\"),!1;var t=[\"type\"];return!!e&&(\"object\"===n(e)&&(Object.keys(e).filter((function(e){return!t.includes(e)})).forEach((function(t){console.warn(\"invalid key inputSettings -> audio -> processor : \".concat(t)),delete e[t]})),!!function(e){if(\"string\"!=typeof e)return!1;if(!Object.values(Qo).includes(e))return console.error(\"inputSettings audio processor type invalid\"),!1;return!0}(e.type)))}function Hs(e){if(na())return console.warn(\"Video processing is not yet supported in React Native\"),!1;var t=[\"type\",\"config\"];if(!e)return!1;if(\"object\"!==n(e))return!1;if(!function(e){if(\"string\"!=typeof e)return!1;if(!Object.values(Go).includes(e))return console.error(\"inputSettings video processor type invalid\"),!1;return!0}(e.type))return!1;if(e.config){if(\"object\"!==n(e.config))return!1;if(!function(e,t){var n=Object.keys(t);if(0===n.length)return!0;var r=\"invalid object in inputSettings -> video -> processor -> config\";switch(e){case Go.BGBLUR:return n.length>1||\"strength\"!==n[0]?(console.error(r),!1):!(\"number\"!=typeof t.strength||t.strength<=0||t.strength>1||isNaN(t.strength))||(console.error(\"\".concat(r,\"; expected: {0 < strength <= 1}, got: \").concat(t.strength)),!1);case Go.BGIMAGE:return!(void 0!==t.source&&!function(e){if(\"default\"===e.source)return e.type=\"default\",!0;if(e.source instanceof ArrayBuffer)return!0;if(Z(e.source))return e.type=\"url\",!!function(e){var t=new URL(e),n=t.pathname;if(\"data:\"===t.protocol)try{var r=n.substring(n.indexOf(\":\")+1,n.indexOf(\";\")).split(\"/\")[1];return Ko.includes(r)}catch(e){return console.error(\"failed to deduce blob content type\",e),!1}var i=n.split(\".\").at(-1).toLowerCase().trim();return Ko.includes(i)}(e.source)||(console.error(\"invalid image type; supported types: [\".concat(Ko.join(\", \"),\"]\")),!1);return t=e.source,n=Number(t),isNaN(n)||!Number.isInteger(n)||n<=0||n>10?(console.error(\"invalid image selection; must be an int, > 0, <= \".concat(10)),!1):(e.type=\"daily-preselect\",!0);var t,n}(t));default:return!0}}(e.type,e.config))return!1}return Object.keys(e).filter((function(e){return!t.includes(e)})).forEach((function(t){console.warn(\"invalid key inputSettings -> video -> processor : \".concat(t)),delete e[t]})),!0}function Gs(e){return\"object\"===n(e)&&(!e.customTrack||e.customTrack instanceof MediaStreamTrack)}function Qs(){var e=Object.values(Go).join(\" | \"),t=Object.values(Qo).join(\" | \");return\"inputSettings must be of the form: { video?: { processor?: { type: [ \".concat(e,\" ], config?: {} } }, audio?: { processor: {type: [ \").concat(t,\" ] } } }\")}function Ys(e){var t=e.allowAllParticipantsKey;return\"receiveSettings must be of the form { [ | \".concat(gi).concat(t?' | \"'.concat(\"*\",'\"'):\"\",\"]: \")+'{ [video: [{ layer: [ | \"inherit\"] } | \"inherit\"]], [screenVideo: [{ layer: [ | \"inherit\"] } | \"inherit\"]] }}}'}function Ks(){return\"customIntegrations should be an object of type \".concat(JSON.stringify(Ps),\".\")}function Xs(e){if(e&&\"object\"!==n(e)||Array.isArray(e))return console.error(\"customTrayButtons should be an Object of the type \".concat(JSON.stringify(Ts),\".\")),!1;if(e)for(var t=0,r=Object.entries(e);t2)throw new Error(\"RemoteMediaPlayerSettings.volume: must be between 0.0 - 2.0\")}}function rc(e,t,n){return!(\"number\"!=typeof e||en)}function ic(e,t){return e&&!t&&delete e.data,e}export{hi as DAILY_ACCESS_LEVEL_FULL,fi as DAILY_ACCESS_LEVEL_LOBBY,vi as DAILY_ACCESS_LEVEL_NONE,pi as DAILY_ACCESS_UNKNOWN,Ai as DAILY_CAMERA_ERROR_CAM_AND_MIC_IN_USE,Pi as DAILY_CAMERA_ERROR_CAM_IN_USE,Ii as DAILY_CAMERA_ERROR_CONSTRAINTS,Oi as DAILY_CAMERA_ERROR_MIC_IN_USE,xi as DAILY_CAMERA_ERROR_NOT_FOUND,ji as DAILY_CAMERA_ERROR_PERMISSIONS,Li as DAILY_CAMERA_ERROR_UNDEF_MEDIADEVICES,Di as DAILY_CAMERA_ERROR_UNKNOWN,Ki as DAILY_EVENT_ACCESS_STATE_UPDATED,Mo as DAILY_EVENT_ACTIVE_SPEAKER_CHANGE,Co as DAILY_EVENT_ACTIVE_SPEAKER_MODE_CHANGE,go as DAILY_EVENT_APP_MSG,$i as DAILY_EVENT_CAMERA_ERROR,Po as DAILY_EVENT_CPU_LOAD_CHANGE,Uo as DAILY_EVENT_ERROR,jo as DAILY_EVENT_EXIT_FULLSCREEN,Oo as DAILY_EVENT_FACE_COUNTS_UPDATED,Ao as DAILY_EVENT_FULLSCREEN,Fi as DAILY_EVENT_IFRAME_LAUNCH_CONFIG,Ni as DAILY_EVENT_IFRAME_READY_FOR_LAUNCH_CONFIG,Ro as DAILY_EVENT_INPUT_SETTINGS_UPDATED,zi as DAILY_EVENT_JOINED_MEETING,qi as DAILY_EVENT_JOINING_MEETING,No as DAILY_EVENT_LANG_UPDATED,Wi as DAILY_EVENT_LEFT_MEETING,Do as DAILY_EVENT_LIVE_STREAMING_ERROR,Lo as DAILY_EVENT_LIVE_STREAMING_STARTED,Io as DAILY_EVENT_LIVE_STREAMING_STOPPED,xo as DAILY_EVENT_LIVE_STREAMING_UPDATED,Vi as DAILY_EVENT_LOADED,Bi as DAILY_EVENT_LOADING,Ui as DAILY_EVENT_LOAD_ATTEMPT_FAILED,So as DAILY_EVENT_LOCAL_SCREEN_SHARE_CANCELED,wo as DAILY_EVENT_LOCAL_SCREEN_SHARE_STARTED,ko as DAILY_EVENT_LOCAL_SCREEN_SHARE_STOPPED,eo as DAILY_EVENT_MEETING_SESSION_DATA_ERROR,Zi as DAILY_EVENT_MEETING_SESSION_STATE_UPDATED,Xi as DAILY_EVENT_MEETING_SESSION_SUMMARY_UPDATED,To as DAILY_EVENT_NETWORK_CONNECTION,Eo as DAILY_EVENT_NETWORK_QUALITY_CHANGE,Bo as DAILY_EVENT_NONFATAL_ERROR,Yi as DAILY_EVENT_PARTICIPANT_COUNTS_UPDATED,Hi as DAILY_EVENT_PARTICIPANT_JOINED,Qi as DAILY_EVENT_PARTICIPANT_LEFT,Gi as DAILY_EVENT_PARTICIPANT_UPDATED,Fo as DAILY_EVENT_RECEIVE_SETTINGS_UPDATED,vo as DAILY_EVENT_RECORDING_DATA,ho as DAILY_EVENT_RECORDING_ERROR,lo as DAILY_EVENT_RECORDING_STARTED,po as DAILY_EVENT_RECORDING_STATS,uo as DAILY_EVENT_RECORDING_STOPPED,fo as DAILY_EVENT_RECORDING_UPLOAD_COMPLETED,yo as DAILY_EVENT_REMOTE_MEDIA_PLAYER_STARTED,bo as DAILY_EVENT_REMOTE_MEDIA_PLAYER_STOPPED,_o as DAILY_EVENT_REMOTE_MEDIA_PLAYER_UPDATED,Ji as DAILY_EVENT_STARTED_CAMERA,Ri as DAILY_EVENT_THEME_UPDATED,io as DAILY_EVENT_TRACK_STARTED,oo as DAILY_EVENT_TRACK_STOPPED,co as DAILY_EVENT_TRANSCRIPTION_ERROR,mo as DAILY_EVENT_TRANSCRIPTION_MSG,ao as DAILY_EVENT_TRANSCRIPTION_STARTED,so as DAILY_EVENT_TRANSCRIPTION_STOPPED,to as DAILY_EVENT_WAITING_PARTICIPANT_ADDED,ro as DAILY_EVENT_WAITING_PARTICIPANT_REMOVED,no as DAILY_EVENT_WAITING_PARTICIPANT_UPDATED,Ti as DAILY_FATAL_ERROR_CONNECTION,yi as DAILY_FATAL_ERROR_EJECTED,Ci as DAILY_FATAL_ERROR_EOL,wi as DAILY_FATAL_ERROR_EXP_ROOM,ki as DAILY_FATAL_ERROR_EXP_TOKEN,Mi as DAILY_FATAL_ERROR_MEETING_FULL,_i as DAILY_FATAL_ERROR_NBF_ROOM,bi as DAILY_FATAL_ERROR_NBF_TOKEN,Ei as DAILY_FATAL_ERROR_NOT_ALLOWED,Si as DAILY_FATAL_ERROR_NO_ROOM,mi as DAILY_RECEIVE_SETTINGS_ALL_PARTICIPANTS_KEY,gi as DAILY_RECEIVE_SETTINGS_BASE_KEY,oi as DAILY_STATE_ERROR,ri as DAILY_STATE_JOINED,ni as DAILY_STATE_JOINING,ii as DAILY_STATE_LEFT,Zr as DAILY_STATE_NEW,ai as DAILY_TRACK_STATE_BLOCKED,ui as DAILY_TRACK_STATE_INTERRUPTED,li as DAILY_TRACK_STATE_LOADING,si as DAILY_TRACK_STATE_OFF,di as DAILY_TRACK_STATE_PLAYABLE,ci as DAILY_TRACK_STATE_SENDABLE,js as default};\n","import { CoreContext } from '../context'\nimport type { Callback } from '../events'\n\nexport function pTimeout(promise: Promise, timeout: number): Promise {\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(Error('Promise timed out'))\n }, timeout)\n\n promise\n .then((val) => {\n clearTimeout(timeoutId)\n return resolve(val)\n })\n .catch(reject)\n })\n}\n\nexport function sleep(timeoutInMs: number): Promise {\n return new Promise((resolve) => setTimeout(resolve, timeoutInMs))\n}\n\n/**\n * @param ctx\n * @param callback - the function to invoke\n * @param delay - aka \"timeout\". The amount of time in ms to wait before invoking the callback.\n */\nexport function invokeCallback(\n ctx: Ctx,\n callback: Callback,\n delay: number\n): Promise {\n const cb = () => {\n try {\n return Promise.resolve(callback(ctx))\n } catch (err) {\n return Promise.reject(err)\n }\n }\n\n return (\n sleep(delay)\n // pTimeout ensures that the callback can't cause the context to hang\n .then(() => pTimeout(cb(), 1000))\n .catch((err) => {\n ctx?.log('warn', 'Callback Error', { error: err })\n ctx?.stats.increment('callback_error')\n })\n .then(() => ctx)\n )\n}\n","export type LogLevel = 'debug' | 'info' | 'warn' | 'error'\nexport type LogMessage = {\n level: LogLevel\n message: string\n time?: Date\n extras?: Record\n}\n\nexport interface GenericLogger {\n log(level: LogLevel, message: string, extras?: object): void\n flush(): void\n logs: LogMessage[]\n}\n\nexport class CoreLogger implements GenericLogger {\n private _logs: LogMessage[] = []\n\n log(level: LogLevel, message: string, extras?: object) {\n const time = new Date()\n this._logs.push({\n level,\n message,\n time,\n extras,\n })\n }\n\n public get logs(): LogMessage[] {\n return this._logs\n }\n\n public flush(): void {\n if (this.logs.length > 1) {\n const formatted = this._logs.reduce((logs, log) => {\n const line = {\n ...log,\n json: JSON.stringify(log.extras, null, ' '),\n extras: log.extras,\n }\n\n delete line['time']\n\n let key = log.time?.toISOString() ?? ''\n if (logs[key]) {\n key = `${key}-${Math.random()}`\n }\n\n return {\n ...logs,\n [key]: line,\n }\n }, {} as Record)\n\n // ie doesn't like console.table\n if (console.table) {\n console.table(formatted)\n } else {\n console.log(formatted)\n }\n } else {\n this.logs.forEach((logEntry) => {\n const { level, message, extras } = logEntry\n\n if (level === 'info' || level === 'debug') {\n console.log(message, extras ?? '')\n } else {\n console[level](message, extras ?? '')\n }\n })\n }\n\n this._logs = []\n }\n}\n","import { CoreSegmentEvent } from '../events/interfaces'\n\nimport { v4 as uuid } from '@lukeed/uuid'\nimport { dset } from 'dset'\nimport { CoreLogger, LogLevel, LogMessage } from '../logger'\nimport { CoreStats, CoreMetric, NullStats } from '../stats'\n\nexport interface SerializedContext {\n id: string\n event: CoreSegmentEvent\n logs: LogMessage[]\n metrics?: CoreMetric[]\n}\n\nexport interface ContextFailedDelivery {\n reason: unknown\n}\n\nexport interface CancelationOptions {\n retry?: boolean\n reason?: string\n type?: string\n}\n\nexport class ContextCancelation {\n retry: boolean\n type: string\n reason?: string\n\n constructor(options: CancelationOptions) {\n this.retry = options.retry ?? true\n this.type = options.type ?? 'plugin Error'\n this.reason = options.reason ?? ''\n }\n}\n\nexport abstract class CoreContext<\n Event extends CoreSegmentEvent = CoreSegmentEvent\n> {\n event: Event\n logger: CoreLogger\n stats: CoreStats\n attempts = 0\n\n private _failedDelivery?: ContextFailedDelivery\n private _id: string\n\n constructor(\n event: Event,\n id = uuid(),\n stats: CoreStats = new NullStats(),\n logger = new CoreLogger()\n ) {\n this.event = event\n this._id = id\n this.logger = logger\n this.stats = stats\n }\n\n static system(): void {\n // This should be overridden by the subclass to return an instance of the subclass.\n }\n\n isSame(other: CoreContext): boolean {\n return other.id === this.id\n }\n\n cancel(error?: Error | ContextCancelation): never {\n if (error) {\n throw error\n }\n\n throw new ContextCancelation({ reason: 'Context Cancel' })\n }\n\n log(level: LogLevel, message: string, extras?: object): void {\n this.logger.log(level, message, extras)\n }\n\n get id(): string {\n return this._id\n }\n\n updateEvent(path: string, val: unknown): Event {\n // Don't allow integrations that are set to false to be overwritten with integration settings.\n if (path.split('.')[0] === 'integrations') {\n const integrationName = path.split('.')[1]\n\n if (this.event.integrations?.[integrationName] === false) {\n return this.event\n }\n }\n\n dset(this.event, path, val)\n return this.event\n }\n\n failedDelivery(): ContextFailedDelivery | undefined {\n return this._failedDelivery\n }\n\n setFailedDelivery(options: ContextFailedDelivery) {\n this._failedDelivery = options\n }\n\n logs(): LogMessage[] {\n return this.logger.logs\n }\n\n flush(): void {\n this.logger.flush()\n this.stats.flush()\n }\n\n toJSON(): SerializedContext {\n return {\n id: this._id,\n event: this.event,\n logs: this.logger.logs,\n metrics: this.stats.metrics,\n }\n }\n}\n","import { Emitter } from '@segment/analytics-generic-utils'\nimport { backoff } from './backoff'\n\n/**\n * @internal\n */\nexport const ON_REMOVE_FROM_FUTURE = 'onRemoveFromFuture'\n\ninterface QueueItem {\n id: string\n}\n\nexport class PriorityQueue extends Emitter {\n protected future: Item[] = []\n protected queue: Item[]\n protected seen: Record\n\n public maxAttempts: number\n\n constructor(\n maxAttempts: number,\n queue: Item[],\n seen?: Record\n ) {\n super()\n this.maxAttempts = maxAttempts\n this.queue = queue\n this.seen = seen ?? {}\n }\n\n push(...items: Item[]): boolean[] {\n const accepted = items.map((operation) => {\n const attempts = this.updateAttempts(operation)\n\n if (attempts > this.maxAttempts || this.includes(operation)) {\n return false\n }\n\n this.queue.push(operation)\n return true\n })\n\n this.queue = this.queue.sort(\n (a, b) => this.getAttempts(a) - this.getAttempts(b)\n )\n return accepted\n }\n\n pushWithBackoff(item: Item): boolean {\n if (this.getAttempts(item) === 0) {\n return this.push(item)[0]\n }\n\n const attempt = this.updateAttempts(item)\n\n if (attempt > this.maxAttempts || this.includes(item)) {\n return false\n }\n\n const timeout = backoff({ attempt: attempt - 1 })\n\n setTimeout(() => {\n this.queue.push(item)\n // remove from future list\n this.future = this.future.filter((f) => f.id !== item.id)\n // Lets listeners know that a 'future' message is now available in the queue\n this.emit(ON_REMOVE_FROM_FUTURE)\n }, timeout)\n\n this.future.push(item)\n return true\n }\n\n public getAttempts(item: Item): number {\n return this.seen[item.id] ?? 0\n }\n\n public updateAttempts(item: Item): number {\n this.seen[item.id] = this.getAttempts(item) + 1\n return this.getAttempts(item)\n }\n\n includes(item: Item): boolean {\n return (\n this.queue.includes(item) ||\n this.future.includes(item) ||\n Boolean(this.queue.find((i) => i.id === item.id)) ||\n Boolean(this.future.find((i) => i.id === item.id))\n )\n }\n\n pop(): Item | undefined {\n return this.queue.shift()\n }\n\n public get length(): number {\n return this.queue.length\n }\n\n public get todo(): number {\n return this.queue.length + this.future.length\n }\n}\n","type BackoffParams = {\n /** The number of milliseconds before starting the first retry. Default is 500 */\n minTimeout?: number\n\n /** The maximum number of milliseconds between two retries. Default is Infinity */\n maxTimeout?: number\n\n /** The exponential factor to use. Default is 2. */\n factor?: number\n\n /** The current attempt */\n attempt: number\n}\n\nexport function backoff(params: BackoffParams): number {\n const random = Math.random() + 1\n const {\n minTimeout = 500,\n factor = 2,\n attempt,\n maxTimeout = Infinity,\n } = params\n return Math.min(random * minTimeout * Math.pow(factor, attempt), maxTimeout)\n}\n","import { CoreContext, ContextCancelation } from '../context'\nimport { CorePlugin } from '../plugins'\n\nasync function tryAsync(fn: () => T | Promise): Promise {\n try {\n return await fn()\n } catch (err) {\n return Promise.reject(err)\n }\n}\n\nexport function attempt(\n ctx: Ctx,\n plugin: CorePlugin\n): Promise {\n ctx.log('debug', 'plugin', { plugin: plugin.name })\n const start = new Date().getTime()\n\n const hook = plugin[ctx.event.type]\n if (hook === undefined) {\n return Promise.resolve(ctx)\n }\n\n const newCtx = tryAsync(() => hook.apply(plugin, [ctx]))\n .then((ctx) => {\n const done = new Date().getTime() - start\n ctx.stats.gauge('plugin_time', done, [`plugin:${plugin.name}`])\n\n return ctx\n })\n .catch((err: Error | ContextCancelation) => {\n if (\n err instanceof ContextCancelation &&\n err.type === 'middleware_cancellation'\n ) {\n throw err\n }\n\n if (err instanceof ContextCancelation) {\n ctx.log('warn', err.type, {\n plugin: plugin.name,\n error: err,\n })\n\n return err\n }\n\n ctx.log('error', 'plugin Error', {\n plugin: plugin.name,\n error: err,\n })\n ctx.stats.increment('plugin_error', 1, [`plugin:${plugin.name}`])\n\n return err\n })\n\n return newCtx\n}\n\nexport function ensure(\n ctx: Ctx,\n plugin: CorePlugin\n): Promise {\n return attempt(ctx, plugin).then((newContext) => {\n if (newContext instanceof CoreContext) {\n return newContext\n }\n\n ctx.log('debug', 'Context canceled')\n ctx.stats.increment('context_canceled')\n ctx.cancel(newContext)\n })\n}\n","type CompactMetricType = 'g' | 'c'\n\nexport type CoreMetricType = 'gauge' | 'counter'\n\nexport interface CoreMetric {\n metric: string\n value: number\n type: CoreMetricType\n tags: string[]\n timestamp: number // unit milliseconds\n}\n\nexport interface CompactMetric {\n m: string // metric name\n v: number // value\n k: CompactMetricType\n t: string[] // tags\n e: number // timestamp in unit milliseconds\n}\n\nconst compactMetricType = (type: CoreMetricType): CompactMetricType => {\n const enums: Record = {\n gauge: 'g',\n counter: 'c',\n }\n return enums[type]\n}\n\nexport abstract class CoreStats {\n metrics: CoreMetric[] = []\n increment(metric: string, by = 1, tags?: string[]): void {\n this.metrics.push({\n metric,\n value: by,\n tags: tags ?? [],\n type: 'counter',\n timestamp: Date.now(),\n })\n }\n\n gauge(metric: string, value: number, tags?: string[]): void {\n this.metrics.push({\n metric,\n value,\n tags: tags ?? [],\n type: 'gauge',\n timestamp: Date.now(),\n })\n }\n\n flush(): void {\n const formatted = this.metrics.map((m) => ({\n ...m,\n tags: m.tags.join(','),\n }))\n // ie doesn't like console.table\n if (console.table) {\n console.table(formatted)\n } else {\n console.log(formatted)\n }\n this.metrics = []\n }\n\n /**\n * compact keys for smaller payload\n */\n serialize(): CompactMetric[] {\n return this.metrics.map((m) => {\n return {\n m: m.metric,\n v: m.value,\n t: m.tags,\n k: compactMetricType(m.type),\n e: m.timestamp,\n }\n })\n }\n}\n\nexport class NullStats extends CoreStats {\n override gauge(..._args: Parameters) {}\n override increment(..._args: Parameters) {}\n override flush(..._args: Parameters) {}\n override serialize(..._args: Parameters) {\n return []\n }\n}\n","export function isString(obj: unknown): obj is string {\n return typeof obj === 'string'\n}\n\nexport function isNumber(obj: unknown): obj is number {\n return typeof obj === 'number'\n}\n\nexport function isFunction(obj: unknown): obj is Function {\n return typeof obj === 'function'\n}\n\nexport function exists(val: unknown): val is NonNullable {\n return val !== undefined && val !== null\n}\n\nexport function isPlainObject(\n obj: unknown\n): obj is Record {\n return (\n Object.prototype.toString.call(obj).slice(8, -1).toLowerCase() === 'object'\n )\n}\n","/**\n * Return a promise that can be externally resolved\n */\nexport const createDeferred = () => {\n let resolve!: (value: T | PromiseLike) => void\n let reject!: (reason: any) => void\n let settled = false\n const promise = new Promise((_resolve, _reject) => {\n resolve = (...args) => {\n settled = true\n _resolve(...args)\n }\n reject = (...args) => {\n settled = true\n _reject(...args)\n }\n })\n\n return {\n resolve,\n reject,\n promise,\n isSettled: () => settled,\n }\n}\n","type EventName = string\ntype EventFnArgs = any[]\ntype EmitterContract = Record\n\nexport interface EmitterOptions {\n /** How many event listeners for a particular event before emitting a warning (0 = disabled)\n * @default 10\n **/\n maxListeners?: number\n}\n\n/**\n * Event Emitter that takes the expected contract as a generic\n * @example\n * ```ts\n * type Contract = {\n * delivery_success: [DeliverySuccessResponse, Metrics],\n * delivery_failure: [DeliveryError]\n * }\n * new Emitter()\n * .on('delivery_success', (res, metrics) => ...)\n * .on('delivery_failure', (err) => ...)\n * ```\n */\nexport class Emitter {\n maxListeners: number\n constructor(options?: EmitterOptions) {\n this.maxListeners = options?.maxListeners ?? 10\n }\n private callbacks: Partial = {}\n private warned = false\n\n private warnIfPossibleMemoryLeak(\n event: EventName\n ) {\n if (this.warned) {\n return\n }\n if (\n this.maxListeners &&\n this.callbacks[event]!.length > this.maxListeners\n ) {\n console.warn(\n `Event Emitter: Possible memory leak detected; ${String(\n event\n )} has exceeded ${this.maxListeners} listeners.`\n )\n this.warned = true\n }\n }\n\n on(\n event: EventName,\n callback: (...args: Contract[EventName]) => void\n ): this {\n if (!this.callbacks[event]) {\n this.callbacks[event] = [callback] as Contract[EventName]\n } else {\n this.callbacks[event]!.push(callback)\n this.warnIfPossibleMemoryLeak(event)\n }\n return this\n }\n\n once(\n event: EventName,\n callback: (...args: Contract[EventName]) => void\n ): this {\n const on = (...args: Contract[EventName]): void => {\n this.off(event, on)\n callback.apply(this, args)\n }\n\n this.on(event, on)\n return this\n }\n\n off(\n event: EventName,\n callback: (...args: Contract[EventName]) => void\n ): this {\n const fns = this.callbacks[event] ?? []\n const without = fns.filter((fn) => fn !== callback) as Contract[EventName]\n this.callbacks[event] = without\n return this\n }\n\n emit(\n event: EventName,\n ...args: Contract[EventName]\n ): this {\n const callbacks = this.callbacks[event] ?? []\n callbacks.forEach((callback) => {\n callback.apply(this, args)\n })\n return this\n }\n}\n","import { isBrowser } from '../environment'\n\nexport function isOnline(): boolean {\n if (isBrowser()) {\n return window.navigator.onLine\n }\n\n return true\n}\n\nexport function isOffline(): boolean {\n return !isOnline()\n}\n","export const SEGMENT_API_HOST = 'api.segment.io/v1'\n","import {\n CoreContext,\n ContextCancelation,\n ContextFailedDelivery,\n SerializedContext,\n CancelationOptions,\n} from '@segment/analytics-core'\nimport { SegmentEvent } from '../events/interfaces'\nimport { Stats } from '../stats'\n\nexport class Context extends CoreContext {\n static override system() {\n return new this({ type: 'track', event: 'system' })\n }\n constructor(event: SegmentEvent, id?: string) {\n super(event, id, new Stats())\n }\n}\n\nexport { ContextCancelation }\nexport type { ContextFailedDelivery, SerializedContext, CancelationOptions }\n","export function isBrowser(): boolean {\n return typeof window !== 'undefined'\n}\n\nexport function isServer(): boolean {\n return !isBrowser()\n}\n","/**\n * Tries to gets the unencoded version of an encoded component of a\n * Uniform Resource Identifier (URI). If input string is malformed,\n * returns it back as-is.\n *\n * Note: All occurences of the `+` character become ` ` (spaces).\n **/\nexport function gracefulDecodeURIComponent(\n encodedURIComponent: string\n): string {\n try {\n return decodeURIComponent(encodedURIComponent.replace(/\\+/g, ' '))\n } catch {\n return encodedURIComponent\n }\n}\n","import { fetch } from '../../lib/fetch'\nimport { version } from '../../generated/version'\nimport { getVersionType } from '../../lib/version-type'\nimport { SEGMENT_API_HOST } from '../constants'\n\nexport interface MetricsOptions {\n host?: string\n sampleRate?: number\n flushTimer?: number\n maxQueueSize?: number\n protocol?: 'http' | 'https'\n}\n\n/**\n * Type expected by the segment metrics API endpoint\n */\ntype RemoteMetric = {\n type: 'Counter'\n metric: string\n value: 1\n tags: {\n library: string\n library_version: string\n [key: string]: string\n }\n}\n\nconst createRemoteMetric = (\n metric: string,\n tags: string[],\n versionType: 'web' | 'npm'\n): RemoteMetric => {\n const formattedTags = tags.reduce((acc, t) => {\n const [k, v] = t.split(':')\n acc[k] = v\n return acc\n }, {} as Record)\n\n return {\n type: 'Counter',\n metric,\n value: 1,\n tags: {\n ...formattedTags,\n library: 'analytics.js',\n library_version:\n versionType === 'web' ? `next-${version}` : `npm:next-${version}`,\n },\n }\n}\n\nfunction logError(err: unknown): void {\n console.error('Error sending segment performance metrics', err)\n}\n\nexport class RemoteMetrics {\n private host: string\n private flushTimer: number\n private maxQueueSize: number\n private protocol: string\n\n sampleRate: number\n queue: RemoteMetric[]\n\n constructor(options?: MetricsOptions) {\n this.host = options?.host ?? SEGMENT_API_HOST\n this.sampleRate = options?.sampleRate ?? 1\n this.flushTimer = options?.flushTimer ?? 30 * 1000 /* 30s */\n this.maxQueueSize = options?.maxQueueSize ?? 20\n this.protocol = options?.protocol ?? 'https'\n\n this.queue = []\n\n if (this.sampleRate > 0) {\n let flushing = false\n\n const run = (): void => {\n if (flushing) {\n return\n }\n\n flushing = true\n this.flush().catch(logError)\n\n flushing = false\n\n setTimeout(run, this.flushTimer)\n }\n run()\n }\n }\n\n increment(metric: string, tags: string[]): void {\n // All metrics are part of an allow list in Tracking API\n if (!metric.includes('analytics_js.')) {\n return\n }\n\n // /m doesn't like empty tags\n if (tags.length === 0) {\n return\n }\n\n if (Math.random() > this.sampleRate) {\n return\n }\n\n if (this.queue.length >= this.maxQueueSize) {\n return\n }\n\n const remoteMetric = createRemoteMetric(metric, tags, getVersionType())\n this.queue.push(remoteMetric)\n\n if (metric.includes('error')) {\n this.flush().catch(logError)\n }\n }\n\n async flush(): Promise {\n if (this.queue.length <= 0) {\n return\n }\n\n await this.send().catch((error) => {\n logError(error)\n this.sampleRate = 0\n })\n }\n\n private async send(): Promise {\n const payload = { series: this.queue }\n this.queue = []\n\n const headers = { 'Content-Type': 'text/plain' }\n const url = `${this.protocol}://${this.host}/m`\n\n return fetch(url, {\n headers,\n body: JSON.stringify(payload),\n method: 'POST',\n })\n }\n}\n","import { CoreStats } from '@segment/analytics-core'\nimport { MetricsOptions, RemoteMetrics } from './remote-metrics'\n\nlet remoteMetrics: RemoteMetrics | undefined\n\nexport class Stats extends CoreStats {\n static initRemoteMetrics(options?: MetricsOptions) {\n remoteMetrics = new RemoteMetrics(options)\n }\n\n override increment(metric: string, by?: number, tags?: string[]): void {\n super.increment(metric, by, tags)\n remoteMetrics?.increment(metric, tags ?? [])\n }\n}\n","import { Context } from '../context'\n\nexport interface RecordIntegrationMetricProps {\n integrationName: string\n methodName: string\n didError?: boolean\n type: 'classic' | 'action'\n}\n\nexport function recordIntegrationMetric(\n ctx: Context,\n {\n methodName,\n integrationName,\n type,\n didError = false,\n }: RecordIntegrationMetricProps\n): void {\n ctx.stats.increment(\n `analytics_js.integration.invoke${didError ? '.error' : ''}`,\n 1,\n [\n `method:${methodName}`,\n `integration_name:${integrationName}`,\n `type:${type}`,\n ]\n )\n}\n","// This file is generated.\nexport const version = '1.70.0'\n","export default function(url, options) {\n\toptions = options || {};\n\treturn new Promise( (resolve, reject) => {\n\t\tconst request = new XMLHttpRequest();\n\t\tconst keys = [];\n\t\tconst all = [];\n\t\tconst headers = {};\n\n\t\tconst response = () => ({\n\t\t\tok: (request.status/100|0) == 2,\t\t// 200-299\n\t\t\tstatusText: request.statusText,\n\t\t\tstatus: request.status,\n\t\t\turl: request.responseURL,\n\t\t\ttext: () => Promise.resolve(request.responseText),\n\t\t\tjson: () => Promise.resolve(request.responseText).then(JSON.parse),\n\t\t\tblob: () => Promise.resolve(new Blob([request.response])),\n\t\t\tclone: response,\n\t\t\theaders: {\n\t\t\t\tkeys: () => keys,\n\t\t\t\tentries: () => all,\n\t\t\t\tget: n => headers[n.toLowerCase()],\n\t\t\t\thas: n => n.toLowerCase() in headers\n\t\t\t}\n\t\t});\n\n\t\trequest.open(options.method || 'get', url, true);\n\n\t\trequest.onload = () => {\n\t\t\trequest.getAllResponseHeaders().replace(/^(.*?):[^\\S\\n]*([\\s\\S]*?)$/gm, (m, key, value) => {\n\t\t\t\tkeys.push(key = key.toLowerCase());\n\t\t\t\tall.push([key, value]);\n\t\t\t\theaders[key] = headers[key] ? `${headers[key]},${value}` : value;\n\t\t\t});\n\t\t\tresolve(response());\n\t\t};\n\n\t\trequest.onerror = reject;\n\n\t\trequest.withCredentials = options.credentials=='include';\n\n\t\tfor (const i in options.headers) {\n\t\t\trequest.setRequestHeader(i, options.headers[i]);\n\t\t}\n\n\t\trequest.send(options.body || null);\n\t});\n}\n","import unfetch from 'unfetch'\nimport { getGlobal } from './get-global'\n\n/**\n * Wrapper around native `fetch` containing `unfetch` fallback.\n */\nexport const fetch: typeof global.fetch = (...args) => {\n const global = getGlobal()\n return ((global && global.fetch) || unfetch)(...args)\n}\n","// This an imperfect polyfill for globalThis\nexport const 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 return null\n}\n","import { AnalyticsSnippet } from '../browser/standalone-interface'\n\n/**\n * Stores the global window analytics key\n */\nlet _globalAnalyticsKey = 'analytics'\n\n/**\n * Gets the global analytics/buffer\n * @param key name of the window property where the buffer is stored (default: analytics)\n * @returns AnalyticsSnippet\n */\nexport function getGlobalAnalytics(): AnalyticsSnippet | undefined {\n return (window as any)[_globalAnalyticsKey]\n}\n\n/**\n * Replaces the global window key for the analytics/buffer object\n * @param key key name\n */\nexport function setGlobalAnalyticsKey(key: string) {\n _globalAnalyticsKey = key\n}\n\n/**\n * Sets the global analytics object\n * @param analytics analytics snippet\n */\nexport function setGlobalAnalytics(analytics: AnalyticsSnippet): void {\n ;(window as any)[_globalAnalyticsKey] = analytics\n}\n","function findScript(src: string): HTMLScriptElement | undefined {\n const scripts = Array.prototype.slice.call(\n window.document.querySelectorAll('script')\n )\n return scripts.find((s) => s.src === src)\n}\n\nexport function loadScript(\n src: string,\n attributes?: Record\n): Promise {\n const found = findScript(src)\n\n if (found !== undefined) {\n const status = found?.getAttribute('status')\n\n if (status === 'loaded') {\n return Promise.resolve(found)\n }\n\n if (status === 'loading') {\n return new Promise((resolve, reject) => {\n found.addEventListener('load', () => resolve(found))\n found.addEventListener('error', (err) => reject(err))\n })\n }\n }\n\n return new Promise((resolve, reject) => {\n const script = window.document.createElement('script')\n\n script.type = 'text/javascript'\n script.src = src\n script.async = true\n\n script.setAttribute('status', 'loading')\n for (const [k, v] of Object.entries(attributes ?? {})) {\n script.setAttribute(k, v)\n }\n\n script.onload = (): void => {\n script.onerror = script.onload = null\n script.setAttribute('status', 'loaded')\n resolve(script)\n }\n\n script.onerror = (): void => {\n script.onerror = script.onload = null\n script.setAttribute('status', 'error')\n reject(new Error(`Failed to load ${src}`))\n }\n\n const tag = window.document.getElementsByTagName('script')[0]\n tag.parentElement?.insertBefore(script, tag)\n })\n}\n\nexport function unloadScript(src: string): Promise {\n const found = findScript(src)\n\n if (found !== undefined) {\n found.remove()\n }\n\n return Promise.resolve()\n}\n","import { JSONObject, Options } from '../core/events/interfaces'\nimport { CDNSettings } from '../browser'\n\n/**\n * Merge legacy settings and initialized Integration option overrides.\n *\n * This will merge any options that were passed from initialization into\n * overrides for settings that are returned by the Segment CDN.\n *\n * i.e. this allows for passing options directly into destinations from\n * the Analytics constructor.\n */\nexport function mergedOptions(\n cdnSettings: CDNSettings,\n options: Options\n): Record {\n const optionOverrides = Object.entries(options.integrations ?? {}).reduce(\n (overrides, [integration, options]) => {\n if (typeof options === 'object') {\n return {\n ...overrides,\n [integration]: options,\n }\n }\n\n return {\n ...overrides,\n [integration]: {},\n }\n },\n {} as Record\n )\n\n return Object.entries(cdnSettings.integrations).reduce(\n (integrationSettings, [integration, settings]) => {\n return {\n ...integrationSettings,\n [integration]: {\n ...settings,\n ...optionOverrides[integration],\n },\n }\n },\n {} as Record\n )\n}\n","export const pWhile = async (\n condition: (value: T | undefined) => boolean,\n action: () => T | PromiseLike\n): Promise => {\n const loop = async (actionResult: T | undefined): Promise => {\n if (condition(actionResult)) {\n return loop(await action())\n }\n }\n\n return loop(undefined)\n}\n","import { getGlobalAnalytics } from './global-analytics-helper'\nimport { embeddedWriteKey } from './embedded-write-key'\n\nconst analyticsScriptRegex =\n /(https:\\/\\/.*)\\/analytics\\.js\\/v1\\/(?:.*?)\\/(?:platform|analytics.*)?/\nconst getCDNUrlFromScriptTag = (): string | undefined => {\n let cdn: string | undefined\n const scripts = Array.prototype.slice.call(\n document.querySelectorAll('script')\n )\n scripts.forEach((s) => {\n const src = s.getAttribute('src') ?? ''\n const result = analyticsScriptRegex.exec(src)\n\n if (result && result[1]) {\n cdn = result[1]\n }\n })\n return cdn\n}\n\nlet _globalCDN: string | undefined // set globalCDN as in-memory singleton\nconst getGlobalCDNUrl = (): string | undefined => {\n const result = _globalCDN ?? getGlobalAnalytics()?._cdn\n return result\n}\n\nexport const setGlobalCDNUrl = (cdn: string) => {\n const globalAnalytics = getGlobalAnalytics()\n if (globalAnalytics) {\n globalAnalytics._cdn = cdn\n }\n _globalCDN = cdn\n}\n\nexport const getCDN = (): string => {\n const globalCdnUrl = getGlobalCDNUrl()\n\n if (globalCdnUrl) return globalCdnUrl\n\n const cdnFromScriptTag = getCDNUrlFromScriptTag()\n\n if (cdnFromScriptTag) {\n return cdnFromScriptTag\n } else {\n // it's possible that the CDN is not found in the page because:\n // - the script is loaded through a proxy\n // - the script is removed after execution\n // in this case, we fall back to the default Segment CDN\n return `https://cdn.segment.com`\n }\n}\n\nexport const getNextIntegrationsURL = () => {\n const cdn = getCDN()\n return `${cdn}/next-integrations`\n}\n\n/**\n * Replaces the CDN URL in the script tag with the one from Analytics.js 1.0\n *\n * @returns the path to Analytics JS 1.0\n **/\nexport function getLegacyAJSPath(): string {\n const writeKey = embeddedWriteKey() ?? getGlobalAnalytics()?._writeKey\n\n const scripts = Array.prototype.slice.call(\n document.querySelectorAll('script')\n )\n let path: string | undefined = undefined\n\n for (const s of scripts) {\n const src = s.getAttribute('src') ?? ''\n const result = analyticsScriptRegex.exec(src)\n\n if (result && result[1]) {\n path = src\n break\n }\n }\n\n if (path) {\n return path.replace('analytics.min.js', 'analytics.classic.js')\n }\n\n return `https://cdn.segment.com/analytics.js/v1/${writeKey}/analytics.classic.js`\n}\n","import { PriorityQueue } from '.'\nimport { Context, SerializedContext } from '../../core/context'\nimport { isBrowser } from '../../core/environment'\n\nlet loc:\n | Storage\n | { getItem: () => void; setItem: () => void; removeItem: () => void } = {\n getItem() {},\n setItem() {},\n removeItem() {},\n}\n\ntry {\n loc = isBrowser() && window.localStorage ? window.localStorage : loc\n} catch (err) {\n console.warn('Unable to access localStorage', err)\n}\n\nfunction persisted(key: string): Context[] {\n const items = loc.getItem(key)\n return (items ? JSON.parse(items) : []).map(\n (p: SerializedContext) => new Context(p.event, p.id)\n )\n}\n\nfunction persistItems(key: string, items: Context[]): void {\n const existing = persisted(key)\n const all = [...items, ...existing]\n\n const merged = all.reduce((acc, item) => {\n return {\n ...acc,\n [item.id]: item,\n }\n }, {} as Record)\n\n loc.setItem(key, JSON.stringify(Object.values(merged)))\n}\n\nfunction seen(key: string): Record {\n const stored = loc.getItem(key)\n return stored ? JSON.parse(stored) : {}\n}\n\nfunction persistSeen(key: string, memory: Record): void {\n const stored = seen(key)\n\n loc.setItem(\n key,\n JSON.stringify({\n ...stored,\n ...memory,\n })\n )\n}\n\nfunction remove(key: string): void {\n loc.removeItem(key)\n}\n\nconst now = (): number => new Date().getTime()\n\nfunction mutex(key: string, onUnlock: Function, attempt = 0): void {\n const lockTimeout = 50\n const lockKey = `persisted-queue:v1:${key}:lock`\n\n const expired = (lock: number): boolean => new Date().getTime() > lock\n const rawLock = loc.getItem(lockKey)\n const lock = rawLock ? (JSON.parse(rawLock) as number) : null\n\n const allowed = lock === null || expired(lock)\n if (allowed) {\n loc.setItem(lockKey, JSON.stringify(now() + lockTimeout))\n onUnlock()\n loc.removeItem(lockKey)\n return\n }\n\n if (!allowed && attempt < 3) {\n setTimeout(() => {\n mutex(key, onUnlock, attempt + 1)\n }, lockTimeout)\n } else {\n console.error('Unable to retrieve lock')\n }\n}\n\nexport class PersistedPriorityQueue extends PriorityQueue {\n constructor(maxAttempts: number, key: string) {\n super(maxAttempts, [])\n\n const itemsKey = `persisted-queue:v1:${key}:items`\n const seenKey = `persisted-queue:v1:${key}:seen`\n\n let saved: Context[] = []\n let lastSeen: Record = {}\n\n mutex(key, () => {\n try {\n saved = persisted(itemsKey)\n lastSeen = seen(seenKey)\n remove(itemsKey)\n remove(seenKey)\n\n this.queue = [...saved, ...this.queue]\n this.seen = { ...lastSeen, ...this.seen }\n } catch (err) {\n console.error(err)\n }\n })\n\n window.addEventListener('pagehide', () => {\n // we deliberately want to use the less powerful 'pagehide' API to only persist on events where the analytics instance gets destroyed, and not on tab away.\n if (this.todo > 0) {\n const items = [...this.queue, ...this.future]\n try {\n mutex(key, () => {\n persistItems(itemsKey, items)\n persistSeen(seenKey, this.seen)\n })\n } catch (err) {\n console.error(err)\n }\n }\n })\n }\n}\n","import {\n Alias,\n Facade,\n Group,\n Identify,\n Options,\n Page,\n Screen,\n Track,\n} from '@segment/facade'\nimport { SegmentEvent } from '../core/events'\n\nexport type SegmentFacade = Facade & {\n obj: SegmentEvent\n}\n\nexport function toFacade(evt: SegmentEvent, options?: Options): SegmentFacade {\n let fcd = new Facade(evt, options)\n\n if (evt.type === 'track') {\n fcd = new Track(evt, options)\n }\n\n if (evt.type === 'identify') {\n fcd = new Identify(evt, options)\n }\n\n if (evt.type === 'page') {\n fcd = new Page(evt, options)\n }\n\n if (evt.type === 'alias') {\n fcd = new Alias(evt, options)\n }\n\n if (evt.type === 'group') {\n fcd = new Group(evt, options)\n }\n\n if (evt.type === 'screen') {\n fcd = new Screen(evt, options)\n }\n\n Object.defineProperty(fcd, 'obj', {\n value: evt,\n writable: true,\n })\n\n return fcd as SegmentFacade\n}\n","// Default value will be updated to 'web' in `bundle-umd.ts` for web build.\nlet _version: 'web' | 'npm' = 'npm'\n\nexport function setVersionType(version: typeof _version) {\n _version = version\n}\n\nexport function getVersionType(): typeof _version {\n return _version\n}\n","import { Context, ContextCancelation } from '../../core/context'\nimport { SegmentEvent } from '../../core/events'\nimport { Plugin } from '../../core/plugin'\nimport { SegmentFacade, toFacade } from '../../lib/to-facade'\n\nexport interface MiddlewareParams {\n payload: SegmentFacade\n\n integrations?: SegmentEvent['integrations']\n next: (payload: MiddlewareParams['payload'] | null) => void\n}\n\nexport interface DestinationMiddlewareParams {\n payload: SegmentFacade\n integration: string\n next: (payload: MiddlewareParams['payload'] | null) => void\n}\n\nexport type MiddlewareFunction = (\n middleware: MiddlewareParams\n) => void | Promise\n\nexport type DestinationMiddlewareFunction = (\n middleware: DestinationMiddlewareParams\n) => void | Promise\n\nexport async function applyDestinationMiddleware(\n destination: string,\n evt: SegmentEvent,\n middleware: DestinationMiddlewareFunction[]\n): Promise {\n // Clone the event so mutations are localized to a single destination.\n let modifiedEvent = toFacade(evt, {\n clone: true,\n traverse: false,\n }).rawEvent() as SegmentEvent\n async function applyMiddleware(\n event: SegmentEvent,\n fn: DestinationMiddlewareFunction\n ): Promise {\n let nextCalled = false\n let returnedEvent: SegmentEvent | null = null\n\n await fn({\n payload: toFacade(event, {\n clone: true,\n traverse: false,\n }),\n integration: destination,\n next(evt) {\n nextCalled = true\n\n if (evt === null) {\n returnedEvent = null\n }\n\n if (evt) {\n returnedEvent = evt.obj\n }\n },\n })\n\n if (!nextCalled && returnedEvent !== null) {\n returnedEvent = returnedEvent as SegmentEvent\n returnedEvent.integrations = {\n ...event.integrations,\n [destination]: false,\n }\n }\n\n return returnedEvent\n }\n\n for (const md of middleware) {\n const result = await applyMiddleware(modifiedEvent, md)\n if (result === null) {\n return null\n }\n modifiedEvent = result\n }\n\n return modifiedEvent\n}\n\nexport function sourceMiddlewarePlugin(\n fn: MiddlewareFunction,\n integrations: SegmentEvent['integrations']\n): Plugin {\n async function apply(ctx: Context): Promise {\n let nextCalled = false\n\n await fn({\n payload: toFacade(ctx.event, {\n clone: true,\n traverse: false,\n }),\n integrations: integrations ?? {},\n next(evt) {\n nextCalled = true\n if (evt) {\n ctx.event = evt.obj\n }\n },\n })\n\n if (!nextCalled) {\n throw new ContextCancelation({\n retry: false,\n type: 'middleware_cancellation',\n reason: 'Middleware `next` function skipped',\n })\n }\n\n return ctx\n }\n\n return {\n name: `Source Middleware ${fn.name}`,\n type: 'before',\n version: '0.1.0',\n\n isLoaded: (): boolean => true,\n load: (ctx): Promise => Promise.resolve(ctx),\n\n track: apply,\n page: apply,\n identify: apply,\n alias: apply,\n group: apply,\n }\n}\n","\"use strict\";\n\nimport get from \"obj-case\";\n\nfunction trait(a, b) {\n return function () {\n // @ts-ignore\n let traits = this.traits();\n // @ts-ignore\n let props = this.properties ? this.properties() : {};\n\n return (\n get(traits, \"address.\" + a) ||\n get(traits, a) ||\n (b ? get(traits, \"address.\" + b) : null) ||\n (b ? get(traits, b) : null) ||\n get(props, \"address.\" + a) ||\n get(props, a) ||\n (b ? get(props, \"address.\" + b) : null) ||\n (b ? get(props, b) : null)\n );\n };\n}\n\n/**\n * Add address getters to `proto`.\n *\n * @ignore\n * @param {Function} proto\n */\nexport default function (proto) {\n proto.zip = trait(\"postalCode\", \"zip\");\n proto.country = trait(\"country\");\n proto.street = trait(\"street\");\n proto.state = trait(\"state\");\n proto.city = trait(\"city\");\n proto.region = trait(\"region\");\n}\n","\"use strict\";\n\nimport inherit from \"inherits\";\nimport { Facade } from \"./facade\";\n\n/**\n * Initialize a new `Alias` facade with a `dictionary` of arguments.\n *\n * @param {Object} dictionary - The object to wrap.\n * @param {string} [dictionary.from] - The previous ID of the user.\n * @param {string} [dictionary.to] - The new ID of the user.\n * @param {Object} opts - Options about what kind of Facade to create.\n *\n * @augments Facade\n */\nexport function Alias(dictionary, opts) {\n Facade.call(this, dictionary, opts);\n}\n\ninherit(Alias, Facade);\n\n/**\n * Return the type of facade this is. This will always return `\"alias\"`.\n *\n * @return {string}\n */\nAlias.prototype.action = function () {\n return \"alias\";\n};\n\n/**\n * An alias for {@link Alias#action}.\n *\n * @function\n * @return {string}\n */\nAlias.prototype.type = Alias.prototype.action;\n\n/**\n * Get the user's previous ID from `previousId` or `from`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nAlias.prototype.previousId = function () {\n return this.field(\"previousId\") || this.field(\"from\");\n};\n\n/**\n * An alias for {@link Alias#previousId}.\n *\n * @function\n * @return {string}\n */\nAlias.prototype.from = Alias.prototype.previousId;\n\n/**\n * Get the user's new ID from `userId` or `to`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nAlias.prototype.userId = function () {\n return this.field(\"userId\") || this.field(\"to\");\n};\n\n/**\n * An alias for {@link Alias#userId}.\n *\n * @function\n * @return {string}\n */\nAlias.prototype.to = Alias.prototype.userId;\n","export function clone(properties) {\n if (typeof properties !== 'object') return properties\n\n if (Object.prototype.toString.call(properties) === '[object Object]') {\n const temp = {};\n for (const key in properties) {\n if (Object.prototype.hasOwnProperty.call(properties, key)) {\n temp[key] = clone(properties[key]);\n }\n }\n return temp;\n } else if (Array.isArray(properties)) {\n return properties.map(clone);\n } else {\n // this is dangerous because it means this is not cloned\n return properties;\n }\n}\n","\"use strict\";\n\nimport inherit from \"inherits\";\nimport { Facade } from \"./facade\";\n\n/**\n * Initialize a new `Delete` facade with a `dictionary` of arguments.\n *\n * @param {Object} dictionary - The object to wrap.\n * @param {string} [dictionary.category] - The delete category.\n * @param {string} [dictionary.name] - The delete name.\n * @param {string} [dictionary.properties] - The delete properties.\n * @param {Object} opts - Options about what kind of Facade to create.\n *\n * @augments Facade\n */\nexport function Delete(dictionary, opts) {\n Facade.call(this, dictionary, opts);\n}\n\ninherit(Delete, Facade);\n\n/**\n * Return the type of facade this is. This will always return `\"delete\"`.\n *\n * @return {string}\n */\nDelete.prototype.type = function () {\n return \"delete\";\n};\n","\"use strict\";\n\nimport address from \"./address\";\nimport { clone } from \"./clone\";\nimport isEnabled from \"./is-enabled\";\nimport newDate from \"new-date\";\nimport objCase from \"obj-case\";\nimport traverse from \"@segment/isodate-traverse\";\n\n/**\n * A *Facade* is an object meant for creating convience wrappers around\n * objects. When developing integrations, you probably want to look at its\n * subclasses, such as {@link Track} or {@link Identify}, rather than this\n * general-purpose class.\n *\n * This letructor will initialize a new `Facade` with an `obj` of arguments.\n *\n * If the inputted `obj` doesn't have a `timestamp` property, one will be added\n * with the value `new Date()`. Otherwise, the `timestamp` property will be\n * converted to a Date using the `new-date` package.\n *\n * By default, the inputted object will be defensively copied, and all ISO\n * strings present in the string will be converted into Dates.\n *\n * @param {Object} obj - The object to wrap.\n * @param {Object} opts - Options about what kind of Facade to create.\n * @param {boolean} [opts.clone=true] - Whether to make defensive clones. If enabled,\n * the inputted object will be cloned, and any objects derived from this facade\n * will be cloned before being returned.\n * @param {boolean} [opts.traverse=true] - Whether to perform ISODate-Traverse\n * on the inputted object.\n *\n * @see {@link https://github.com/segmentio/new-date|new-date}\n * @see {@link https://github.com/segmentio/isodate-traverse|isodate-traverse}\n */\nexport function Facade (obj, opts) {\n opts = opts || {};\n this.raw = clone(obj);\n if (!(\"clone\" in opts)) opts.clone = true;\n if (opts.clone) obj = clone(obj);\n if (!(\"traverse\" in opts)) opts.traverse = true;\n if (!(\"timestamp\" in obj)) obj.timestamp = new Date();\n else obj.timestamp = newDate(obj.timestamp);\n if (opts.traverse) traverse(obj);\n this.opts = opts;\n this.obj = obj;\n}\n\nconst f = Facade.prototype;\n\n/**\n * Get a potentially-nested field in this facade. `field` should be a\n * period-separated sequence of properties.\n *\n * If the first field passed in points to a function (e.g. the `field` passed\n * in is `a.b.c` and this facade's `obj.a` is a function), then that function\n * will be called, and then the deeper fields will be fetched (using obj-case)\n * from what that function returns. If the first field isn't a function, then\n * this function works just like obj-case.\n *\n * Because this function uses obj-case, the camel- or snake-case of the input\n * is irrelevant.\n *\n * @example\n * YourClass.prototype.height = function() {\n * return this.proxy('getDimensions.height') ||\n * this.proxy('props.size.side_length');\n * }\n * @param {string} field - A sequence of properties, joined by periods (`.`).\n * @return {*} - A property of the inputted object.\n * @see {@link https://github.com/segmentio/obj-case|obj-case}\n */\nf.proxy = function(field) {\n let fields = field.split(\".\");\n field = fields.shift();\n\n // Call a function at the beginning to take advantage of facaded fields\n let obj = this[field] || this.obj[field];\n if (!obj) return obj;\n if (typeof obj === \"function\") obj = obj.call(this) || {};\n if (fields.length === 0) return this.opts.clone ? transform(obj) : obj;\n\n obj = objCase(obj, fields.join(\".\"));\n return this.opts.clone ? transform(obj) : obj;\n};\n\n/**\n * Directly access a specific `field` from the underlying object. Only\n * \"top-level\" fields will work with this function. \"Nested\" fields *will not\n * work* with this function.\n *\n * @param {string} field\n * @return {*}\n */\nf.field = function(field) {\n let obj = this.obj[field];\n return this.opts.clone ? transform(obj) : obj;\n};\n\n/**\n * Utility method to always proxy a particular `field`. In other words, it\n * returns a function that will always return `this.proxy(field)`.\n *\n * @example\n * MyClass.prototype.height = Facade.proxy('options.dimensions.height');\n *\n * @param {string} field\n * @return {Function}\n */\nFacade.proxy = function(field) {\n return function() {\n return this.proxy(field);\n };\n};\n\n/**\n * Utility method to always access a `field`. In other words, it returns a\n * function that will always return `this.field(field)`.\n *\n * @param {string} field\n * @return {Function}\n */\nFacade.field = function(field) {\n return function() {\n return this.field(field);\n };\n};\n\n/**\n * Create a helper function for fetching a \"plural\" thing.\n *\n * The generated method will take the inputted `path` and append an \"s\" to it\n * and calls `this.proxy` with this \"pluralized\" path. If that produces an\n * array, that will be returned. Otherwise, a one-element array containing\n * `this.proxy(path)` will be returned.\n *\n * @example\n * MyClass.prototype.birds = Facade.multi('animals.bird');\n *\n * @param {string} path\n * @return {Function}\n */\nFacade.multi = function(path) {\n return function() {\n let multi = this.proxy(path + \"s\");\n if (Array.isArray(multi)) return multi;\n let one = this.proxy(path);\n if (one) one = [this.opts.clone ? clone(one) : one];\n return one || [];\n };\n};\n\n/**\n * Create a helper function for getting a \"singular\" thing.\n *\n * The generated method will take the inputted path and call\n * `this.proxy(path)`. If a truthy thing is produced, it will be returned.\n * Otherwise, `this.proxy(path + 's')` will be called, and if that produces an\n * array the first element of that array will be returned. Otherwise,\n * `undefined` is returned.\n *\n * @example\n * MyClass.prototype.bird = Facade.one('animals.bird');\n *\n * @param {string} path\n * @return {Function}\n */\nFacade.one = function(path) {\n return function() {\n let one = this.proxy(path);\n if (one) return one;\n let multi = this.proxy(path + \"s\");\n if (Array.isArray(multi)) return multi[0];\n };\n};\n\n/**\n * Gets the underlying object this facade wraps around.\n *\n * If this facade has a property `type`, it will be invoked as a function and\n * will be assigned as the property `type` of the outputted object.\n *\n * @return {Object}\n */\nf.json = function() {\n let ret = this.opts.clone ? clone(this.obj) : this.obj;\n if (this.type) ret.type = this.type();\n return ret;\n};\n\n/**\n * Gets a copy of the unmodified input object this facade wraps around.\n * \n * Unlike the `json` method which does make some subtle modifications \n * to datetime values and the `type` property. This method returns a copy of \n * the unmodified input object\n * \n * @return {Object}\n */\nf.rawEvent = function() {\n return this.raw;\n};\n\n/**\n * Get the options of a call. If an integration is passed, only the options for\n * that integration are included. If the integration is not enabled, then\n * `undefined` is returned.\n *\n * Options are taken from the `options` property of the underlying object,\n * falling back to the object's `context` or simply `{}`.\n *\n * @param {string} integration - The name of the integration to get settings\n * for. Casing does not matter.\n * @return {Object|undefined}\n */\nf.options = function(integration) {\n let obj = this.obj.options || this.obj.context || {};\n let options = this.opts.clone ? clone(obj) : obj;\n if (!integration) return options;\n if (!this.enabled(integration)) return;\n let integrations = this.integrations();\n let value = integrations[integration] || objCase(integrations, integration);\n if (typeof value !== \"object\") value = objCase(this.options(), integration);\n return typeof value === \"object\" ? value : {};\n};\n\n/**\n * An alias for {@link Facade#options}.\n */\nf.context = f.options;\n\n/**\n * Check whether an integration is enabled.\n *\n * Basically, this method checks whether this integration is explicitly\n * enabled. If it isn'texplicitly mentioned, it checks whether it has been\n * enabled at the global level. Some integrations (e.g. Salesforce), cannot\n * enabled by these global event settings.\n *\n * More concretely, the deciding factors here are:\n *\n * 1. If `this.integrations()` has the integration set to `true`, return `true`.\n * 2. If `this.integrations().providers` has the integration set to `true`, return `true`.\n * 3. If integrations are set to default-disabled via global parameters (i.e.\n * `options.providers.all`, `options.all`, or `integrations.all`), then return\n * false.\n * 4. If the integration is one of the special default-deny integrations\n * (currently, only Salesforce), then return false.\n * 5. Else, return true.\n *\n * @param {string} integration\n * @return {boolean}\n */\nf.enabled = function(integration) {\n let allEnabled = this.proxy(\"options.providers.all\");\n if (typeof allEnabled !== \"boolean\") allEnabled = this.proxy(\"options.all\");\n if (typeof allEnabled !== \"boolean\")\n allEnabled = this.proxy(\"integrations.all\");\n if (typeof allEnabled !== \"boolean\") allEnabled = true;\n\n let enabled = allEnabled && isEnabled(integration);\n let options = this.integrations();\n\n // If the integration is explicitly enabled or disabled, use that\n // First, check options.providers for backwards compatibility\n if (options.providers && options.providers.hasOwnProperty(integration)) {\n enabled = options.providers[integration];\n }\n\n // Next, check for the integration's existence in 'options' to enable it.\n // If the settings are a boolean, use that, otherwise it should be enabled.\n if (options.hasOwnProperty(integration)) {\n let settings = options[integration];\n if (typeof settings === \"boolean\") {\n enabled = settings;\n } else {\n enabled = true;\n }\n }\n\n return !!enabled;\n};\n\n/**\n * Get all `integration` options.\n *\n * @ignore\n * @param {string} integration\n * @return {Object}\n */\nf.integrations = function() {\n return (\n this.obj.integrations || this.proxy(\"options.providers\") || this.options()\n );\n};\n\n/**\n * Check whether the user is active.\n *\n * @return {boolean}\n */\nf.active = function() {\n let active = this.proxy(\"options.active\");\n if (active === null || active === undefined) active = true;\n return active;\n};\n\n/**\n * Get `sessionId / anonymousId`.\n *\n * @return {*}\n */\nf.anonymousId = function() {\n return this.field(\"anonymousId\") || this.field(\"sessionId\");\n};\n\n/**\n * An alias for {@link Facade#anonymousId}.\n *\n * @function\n * @return {string}\n */\nf.sessionId = f.anonymousId;\n\n/**\n * Get `groupId` from `context.groupId`.\n *\n * @function\n * @return {string}\n */\nf.groupId = Facade.proxy(\"options.groupId\");\n\n/**\n * Get the call's \"traits\". All event types can pass in traits, though {@link\n * Identify} and {@link Group} override this implementation.\n *\n * Traits are gotten from `options.traits`, augmented with a property `id` with\n * the event's `userId`.\n *\n * The parameter `aliases` is meant to transform keys in `options.traits` into\n * new keys. Each alias like `{ \"xxx\": \"yyy\" }` will take whatever is at `xxx`\n * in the traits, and move it to `yyy`. If `xxx` is a method of this facade,\n * it'll be called as a function instead of treated as a key into the traits.\n *\n * @example\n * let obj = { options: { traits: { foo: \"bar\" } }, anonymousId: \"xxx\" }\n * let facade = new Facade(obj)\n *\n * facade.traits() // { \"foo\": \"bar\" }\n * facade.traits({ \"foo\": \"asdf\" }) // { \"asdf\": \"bar\" }\n * facade.traits({ \"sessionId\": \"rofl\" }) // { \"rofl\": \"xxx\" }\n *\n * @param {Object} aliases - A mapping from keys to the new keys they should be\n * transformed to.\n * @return {Object}\n */\nf.traits = function(aliases) {\n let ret = this.proxy(\"options.traits\") || {};\n let id = this.userId();\n aliases = aliases || {};\n\n if (id) ret.id = id;\n\n for (const alias in aliases) {\n if (Object.prototype.hasOwnProperty.call(aliases, alias)) {\n const value = this[alias] == null\n ? this.proxy(\"options.traits.\" + alias)\n : this[alias]();\n if (value == null) continue;\n ret[aliases[alias]] = value;\n delete ret[alias];\n }\n }\n\n return ret;\n};\n\n/**\n * The library and version of the client used to produce the message.\n *\n * If the library name cannot be determined, it is set to `\"unknown\"`. If the\n * version cannot be determined, it is set to `null`.\n *\n * @return {{name: string, version: string}}\n */\nf.library = function() {\n let library = this.proxy(\"options.library\");\n if (!library) return { name: \"unknown\", version: null };\n if (typeof library === \"string\") return { name: library, version: null };\n return library;\n};\n\n/**\n * Return the device information, falling back to an empty object.\n *\n * Interesting values of `type` are `\"ios\"` and `\"android\"`, but other values\n * are possible if the client is doing something unusual with `context.device`.\n *\n * @return {{type: string}}\n */\nf.device = function() {\n let device = this.proxy(\"context.device\");\n if (typeof device !== \"object\" || device === null) {\n device = {};\n }\n let library = this.library().name;\n if (device.type) return device;\n\n if (library.indexOf(\"ios\") > -1) device.type = \"ios\";\n if (library.indexOf(\"android\") > -1) device.type = \"android\";\n return device;\n};\n\n/**\n * Get the User-Agent from `context.userAgent`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return string\n */\nf.userAgent = Facade.proxy(\"context.userAgent\");\n\n/**\n * Get the timezone from `context.timezone`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return string\n */\nf.timezone = Facade.proxy(\"context.timezone\");\n\n/**\n * Get the timestamp from `context.timestamp`.\n *\n * @function\n * @return string\n */\nf.timestamp = Facade.field(\"timestamp\");\n\n/**\n * Get the channel from `channel`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return string\n */\nf.channel = Facade.field(\"channel\");\n\n/**\n * Get the IP address from `context.ip`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return string\n */\nf.ip = Facade.proxy(\"context.ip\");\n\n/**\n * Get the user ID from `userId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return string\n */\nf.userId = Facade.field(\"userId\");\n\n/**\n * Get the ZIP/Postal code from `traits`, `traits.address`, `properties`, or\n * `properties.address`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @name zip\n * @function\n * @memberof f\n * @return {string}\n */\n\n/**\n * Get the country from `traits`, `traits.address`, `properties`, or\n * `properties.address`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @name country\n * @function\n * @memberof f\n * @return {string}\n */\n\n/**\n * Get the street from `traits`, `traits.address`, `properties`, or\n * `properties.address`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @name street\n * @function\n * @memberof f\n * @return {string}\n */\n\n/**\n * Get the state from `traits`, `traits.address`, `properties`, or\n * `properties.address`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @name state\n * @function\n * @memberof f\n * @return {string}\n */\n\n/**\n * Get the city from `traits`, `traits.address`, `properties`, or\n * `properties.address`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @name city\n * @function\n * @memberof f\n * @return {string}\n */\n\n/**\n * Get the region from `traits`, `traits.address`, `properties`, or\n * `properties.address`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @name region\n * @function\n * @memberof f\n * @return {string}\n */\n\naddress(f);\n\n/**\n * Return the cloned and traversed object\n *\n * @ignore\n * @param {*} obj\n * @return {*}\n */\nfunction transform (obj) {\n return clone(obj);\n}\n","\"use strict\";\n\nimport inherit from \"inherits\";\nimport isEmail from \"./is-email\";\nimport newDate from \"new-date\";\nimport { Facade } from \"./facade\";\n\n/**\n * Initialize a new `Group` facade with a `dictionary` of arguments.\n *\n * @param {Object} dictionary - The object to wrap.\n * @param {string} [dictionary.userId] - The user to add to the group.\n * @param {string} [dictionary.groupId] - The ID of the group.\n * @param {Object} [dictionary.traits] - The traits of the group.\n * @param {Object} opts - Options about what kind of Facade to create.\n *\n * @augments Facade\n */\nexport function Group(dictionary, opts) {\n Facade.call(this, dictionary, opts);\n}\n\ninherit(Group, Facade);\n\nconst g = Group.prototype;\n\n/**\n * Return the type of facade this is. This will always return `\"group\"`.\n *\n * @return {string}\n */\ng.action = function () {\n return \"group\";\n};\n\n/**\n * An alias for {@link Group#action}.\n *\n * @function\n * @return {string}\n */\ng.type = g.action;\n\n/**\n * Get the group ID from `groupId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ng.groupId = Facade.field(\"groupId\");\n\n/**\n * Get the time of creation of the group from `traits.createdAt`,\n * `traits.created`, `properties.createdAt`, or `properties.created`.\n *\n * @return {Date}\n */\ng.created = function () {\n var created =\n this.proxy(\"traits.createdAt\") ||\n this.proxy(\"traits.created\") ||\n this.proxy(\"properties.createdAt\") ||\n this.proxy(\"properties.created\");\n\n if (created) return newDate(created);\n};\n\n/**\n * Get the group's email from `traits.email`, falling back to `groupId` only if\n * it looks like a valid email.\n *\n * @return {string}\n */\ng.email = function () {\n var email = this.proxy(\"traits.email\");\n if (email) return email;\n var groupId = this.groupId();\n if (isEmail(groupId)) return groupId;\n};\n\n/**\n * Get the group's traits. This is identical to how {@link Facade#traits}\n * works, except it looks at `traits.*` instead of `options.traits.*`.\n *\n * Traits are gotten from `traits`, augmented with a property `id` with\n * the event's `groupId`.\n *\n * The parameter `aliases` is meant to transform keys in `traits` into new\n * keys. Each alias like `{ \"xxx\": \"yyy\" }` will take whatever is at `xxx` in\n * the traits, and move it to `yyy`. If `xxx` is a method of this facade, it'll\n * be called as a function instead of treated as a key into the traits.\n *\n * @example\n * var obj = { traits: { foo: \"bar\" }, anonymousId: \"xxx\" }\n * var group = new Group(obj)\n *\n * group.traits() // { \"foo\": \"bar\" }\n * group.traits({ \"foo\": \"asdf\" }) // { \"asdf\": \"bar\" }\n * group.traits({ \"sessionId\": \"rofl\" }) // { \"rofl\": \"xxx\" }\n *\n * @param {Object} aliases - A mapping from keys to the new keys they should be\n * transformed to.\n * @return {Object}\n */\ng.traits = function (aliases) {\n var ret = this.properties();\n var id = this.groupId();\n aliases = aliases || {};\n\n if (id) ret.id = id;\n\n for (const alias in aliases) {\n if (Object.prototype.hasOwnProperty.call(aliases, alias)) {\n const value = this[alias] == null\n ? this.proxy(\"traits.\" + alias)\n : this[alias]();\n if (value == null) continue;\n ret[aliases[alias]] = value;\n delete ret[alias];\n }\n }\n\n return ret;\n};\n\n/**\n * Get the group's name from `traits.name`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\ng.name = Facade.proxy(\"traits.name\");\n\n/**\n * Get the group's industry from `traits.industry`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\ng.industry = Facade.proxy(\"traits.industry\");\n\n/**\n * Get the group's employee count from `traits.employees`.\n *\n * This *should* be a number, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {number}\n */\ng.employees = Facade.proxy(\"traits.employees\");\n\n/**\n * Get the group's properties from `traits` or `properties`, falling back to\n * simply an empty object.\n *\n * @return {Object}\n */\ng.properties = function () {\n // TODO remove this function\n return this.field(\"traits\") || this.field(\"properties\") || {};\n};\n","\"use strict\";\n\nimport { Facade } from \"./facade\";\nimport get from \"obj-case\";\nimport inherit from \"inherits\";\nimport isEmail from \"./is-email\";\nimport newDate from \"new-date\";\n\nlet trim = (str) => str.trim();\n\n/**\n * Initialize a new `Identify` facade with a `dictionary` of arguments.\n *\n * @param {Object} dictionary - The object to wrap.\n * @param {string} [dictionary.userId] - The ID of the user.\n * @param {string} [dictionary.anonymousId] - The anonymous ID of the user.\n * @param {string} [dictionary.traits] - The user's traits.\n * @param {Object} opts - Options about what kind of Facade to create.\n *\n * @augments Facade\n */\nexport function Identify(dictionary, opts) {\n Facade.call(this, dictionary, opts);\n}\n\ninherit(Identify, Facade);\n\nconst i = Identify.prototype;\n\n/**\n * Return the type of facade this is. This will always return `\"identify\"`.\n *\n * @return {string}\n */\ni.action = function () {\n return \"identify\";\n};\n\n/**\n * An alias for {@link Identify#action}.\n *\n * @function\n * @return {string}\n */\ni.type = i.action;\n\n/**\n * Get the user's traits. This is identical to how {@link Facade#traits} works,\n * except it looks at `traits.*` instead of `options.traits.*`.\n *\n * Traits are gotten from `traits`, augmented with a property `id` with\n * the event's `userId`.\n *\n * The parameter `aliases` is meant to transform keys in `traits` into new\n * keys. Each alias like `{ \"xxx\": \"yyy\" }` will take whatever is at `xxx` in\n * the traits, and move it to `yyy`. If `xxx` is a method of this facade, it'll\n * be called as a function instead of treated as a key into the traits.\n *\n * @example\n * let obj = { traits: { foo: \"bar\" }, anonymousId: \"xxx\" }\n * let identify = new Identify(obj)\n *\n * identify.traits() // { \"foo\": \"bar\" }\n * identify.traits({ \"foo\": \"asdf\" }) // { \"asdf\": \"bar\" }\n * identify.traits({ \"sessionId\": \"rofl\" }) // { \"rofl\": \"xxx\" }\n *\n * @param {Object} aliases - A mapping from keys to the new keys they should be\n * transformed to.\n * @return {Object}\n */\ni.traits = function (aliases) {\n let ret = this.field(\"traits\") || {};\n let id = this.userId();\n aliases = aliases || {};\n\n if (id) ret.id = id;\n\n for (let alias in aliases) {\n let value =\n this[alias] == null ? this.proxy(\"traits.\" + alias) : this[alias]();\n if (value == null) continue;\n ret[aliases[alias]] = value;\n if (alias !== aliases[alias]) delete ret[alias];\n }\n\n return ret;\n};\n\n/**\n * Get the user's email from `traits.email`, falling back to `userId` only if\n * it looks like a valid email.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.email = function () {\n let email = this.proxy(\"traits.email\");\n if (email) return email;\n\n let userId = this.userId();\n if (isEmail(userId)) return userId;\n};\n\n/**\n * Get the time of creation of the user from `traits.created` or\n * `traits.createdAt`.\n *\n * @return {Date}\n */\ni.created = function () {\n let created = this.proxy(\"traits.created\") || this.proxy(\"traits.createdAt\");\n if (created) return newDate(created);\n};\n\n/**\n * Get the time of creation of the user's company from `traits.company.created`\n * or `traits.company.createdAt`.\n *\n * @return {Date}\n */\ni.companyCreated = function () {\n let created =\n this.proxy(\"traits.company.created\") ||\n this.proxy(\"traits.company.createdAt\");\n\n if (created) {\n return newDate(created);\n }\n};\n\n/**\n * Get the user's company name from `traits.company.name`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.companyName = function () {\n return this.proxy(\"traits.company.name\");\n};\n\n/**\n * Get the user's name `traits.name`, falling back to combining {@link\n * Identify#firstName} and {@link Identify#lastName} if possible.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.name = function () {\n let name = this.proxy(\"traits.name\");\n if (typeof name === \"string\") {\n return trim(name);\n }\n\n let firstName = this.firstName();\n let lastName = this.lastName();\n if (firstName && lastName) {\n return trim(firstName + \" \" + lastName);\n }\n};\n\n/**\n * Get the user's first name from `traits.firstName`, optionally splitting it\n * out of a the full name if that's all that was provided.\n *\n * Splitting the full name works on the assumption that the full name is of the\n * form \"FirstName LastName\"; it will not work for non-Western names.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.firstName = function () {\n let firstName = this.proxy(\"traits.firstName\");\n if (typeof firstName === \"string\") {\n return trim(firstName);\n }\n\n let name = this.proxy(\"traits.name\");\n if (typeof name === \"string\") {\n return trim(name).split(\" \")[0];\n }\n};\n\n/**\n * Get the user's last name from `traits.lastName`, optionally splitting it out\n * of a the full name if that's all that was provided.\n *\n * Splitting the full name works on the assumption that the full name is of the\n * form \"FirstName LastName\"; it will not work for non-Western names.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.lastName = function () {\n let lastName = this.proxy(\"traits.lastName\");\n if (typeof lastName === \"string\") {\n return trim(lastName);\n }\n\n let name = this.proxy(\"traits.name\");\n if (typeof name !== \"string\") {\n return;\n }\n\n let space = trim(name).indexOf(\" \");\n if (space === -1) {\n return;\n }\n\n return trim(name.substr(space + 1));\n};\n\n/**\n * Get the user's \"unique id\" from `userId`, `traits.username`, or\n * `traits.email`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.uid = function () {\n return this.userId() || this.username() || this.email();\n};\n\n/**\n * Get the user's description from `traits.description` or `traits.background`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.description = function () {\n return this.proxy(\"traits.description\") || this.proxy(\"traits.background\");\n};\n\n/**\n * Get the user's age from `traits.age`, falling back to computing it from\n * `traits.birthday` and the current time.\n *\n * @return {number}\n */\ni.age = function () {\n let date = this.birthday();\n let age = get(this.traits(), \"age\");\n if (age != null) return age;\n if (!(date instanceof Date)) return;\n let now = new Date();\n return now.getFullYear() - date.getFullYear();\n};\n\n/**\n * Get the URL of the user's avatar from `traits.avatar`, `traits.photoUrl`, or\n * `traits.avatarUrl`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.avatar = function () {\n let traits = this.traits();\n return (\n get(traits, \"avatar\") || get(traits, \"photoUrl\") || get(traits, \"avatarUrl\")\n );\n};\n\n/**\n * Get the user's job position from `traits.position` or `traits.jobTitle`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.position = function () {\n let traits = this.traits();\n return get(traits, \"position\") || get(traits, \"jobTitle\");\n};\n\n/**\n * Get the user's username from `traits.username`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\ni.username = Facade.proxy(\"traits.username\");\n\n/**\n * Get the user's website from `traits.website`, or if there are multiple in\n * `traits.websites`, return the first one.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\ni.website = Facade.one(\"traits.website\");\n\n/**\n * Get the user's websites from `traits.websites`, or if there is only one in\n * `traits.website`, then wrap it in an array.\n *\n * This *should* be an array of strings, but may not be if the client isn't\n * adhering to the spec.\n *\n * @function\n * @return {array}\n */\ni.websites = Facade.multi(\"traits.website\");\n\n/**\n * Get the user's phone number from `traits.phone`, or if there are multiple in\n * `traits.phones`, return the first one.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\ni.phone = Facade.one(\"traits.phone\");\n\n/**\n * Get the user's phone numbers from `traits.phones`, or if there is only one\n * in `traits.phone`, then wrap it in an array.\n *\n * This *should* be an array of strings, but may not be if the client isn't\n * adhering to the spec.\n *\n * @function\n * @return {array}\n */\ni.phones = Facade.multi(\"traits.phone\");\n\n/**\n * Get the user's address from `traits.address`.\n *\n * This *should* be an object, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {object}\n */\ni.address = Facade.proxy(\"traits.address\");\n\n/**\n * Get the user's gender from `traits.gender`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\ni.gender = Facade.proxy(\"traits.gender\");\n\n/**\n * Get the user's birthday from `traits.birthday`.\n *\n * This *should* be a Date if `opts.traverse` was enabled (it is by default)\n * when letructing this Identify. Otherwise, it should be a string. But it\n * may be neither if the client isn't adhering to the spec.\n * spec.\n *\n * @function\n * @return {object}\n */\ni.birthday = Facade.proxy(\"traits.birthday\");\n","\"use strict\";\n\nimport { Facade } from \"./facade\";\nimport { Alias } from \"./alias\";\nimport { Group } from \"./group\";\nimport { Identify } from \"./identify\";\nimport { Track } from \"./track\";\nimport { Page } from \"./page\";\nimport { Screen } from \"./screen\";\nimport { Delete } from \"./delete\";\n\nexport default {\n ...Facade,\n Alias,\n Group,\n Identify,\n Track,\n Page,\n Screen,\n Delete,\n};\n\nexport { Facade, Alias, Group, Identify, Track, Page, Screen, Delete };\n","const matcher = /.+\\@.+\\..+/;\n\nexport default function isEmail(string) {\n return matcher.test(string);\n}\n","\"use strict\";\n\n// A few integrations are disabled by default. They must be explicitly enabled\n// by setting options[Provider] = true.\nlet disabled = {\n Salesforce: true,\n};\n\n/**\n * Check whether an integration should be enabled by default.\n *\n * @ignore\n * @param {string} integration\n * @return {boolean}\n */\nexport default function (integration) {\n return !disabled[integration];\n}\n","\"use strict\";\n\nimport inherit from \"inherits\";\nimport { Facade } from \"./facade\";\nimport { Track } from \"./track\";\nimport isEmail from \"./is-email\";\n\n/**\n * Initialize a new `Page` facade with a `dictionary` of arguments.\n *\n * @param {Object} dictionary - The object to wrap.\n * @param {string} [dictionary.category] - The page category.\n * @param {string} [dictionary.name] - The page name.\n * @param {string} [dictionary.properties] - The page properties.\n * @param {Object} opts - Options about what kind of Facade to create.\n *\n * @augments Facade\n */\nexport function Page(dictionary, opts) {\n Facade.call(this, dictionary, opts);\n}\n\ninherit(Page, Facade);\n\nconst p = Page.prototype;\n\n/**\n * Return the type of facade this is. This will always return `\"page\"`.\n *\n * @return {string}\n */\np.action = function () {\n return \"page\";\n};\n\n/**\n * An alias for {@link Page#action}.\n *\n * @function\n * @return {string}\n */\np.type = p.action;\n\n/**\n * Get the page category from `category`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.category = Facade.field(\"category\");\n\n/**\n * Get the page name from `name`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.name = Facade.field(\"name\");\n\n/**\n * Get the page title from `properties.title`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.title = Facade.proxy(\"properties.title\");\n\n/**\n * Get the page path from `properties.path`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.path = Facade.proxy(\"properties.path\");\n\n/**\n * Get the page URL from `properties.url`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.url = Facade.proxy(\"properties.url\");\n\n/**\n * Get the HTTP referrer from `context.referrer.url`, `context.page.referrer`,\n * or `properties.referrer`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.referrer = function () {\n return (\n this.proxy(\"context.referrer.url\") ||\n this.proxy(\"context.page.referrer\") ||\n this.proxy(\"properties.referrer\")\n );\n};\n\n/**\n * Get the page's properties. This is identical to how {@link Facade#traits}\n * works, except it looks at `properties.*` instead of `options.traits.*`.\n *\n * Properties are gotten from `properties`, augmented with the page's `name`\n * and `category`.\n *\n * The parameter `aliases` is meant to transform keys in `properties` into new\n * keys. Each alias like `{ \"xxx\": \"yyy\" }` will take whatever is at `xxx` in\n * the traits, and move it to `yyy`. If `xxx` is a method of this facade, it'll\n * be called as a function instead of treated as a key into the traits.\n *\n * @example\n * let obj = { properties: { foo: \"bar\" }, anonymousId: \"xxx\" }\n * let page = new Page(obj)\n *\n * page.traits() // { \"foo\": \"bar\" }\n * page.traits({ \"foo\": \"asdf\" }) // { \"asdf\": \"bar\" }\n * page.traits({ \"sessionId\": \"rofl\" }) // { \"rofl\": \"xxx\" }\n *\n * @param {Object} aliases - A mapping from keys to the new keys they should be\n * transformed to.\n * @return {Object}\n */\np.properties = function (aliases) {\n let props = this.field(\"properties\") || {};\n let category = this.category();\n let name = this.name();\n aliases = aliases || {};\n\n if (category) props.category = category;\n if (name) props.name = name;\n\n for (const alias in aliases) {\n if (Object.prototype.hasOwnProperty.call(aliases, alias)) {\n const value = this[alias] == null\n ? this.proxy(\"properties.\" + alias)\n : this[alias]();\n if (value == null) continue;\n props[aliases[alias]] = value;\n if (alias !== aliases[alias]) delete props[alias];\n }\n }\n\n return props;\n};\n\n/**\n * Get the user's email from `context.traits.email` or `properties.email`,\n * falling back to `userId` if it's a valid email.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.email = function () {\n let email =\n this.proxy(\"context.traits.email\") || this.proxy(\"properties.email\");\n if (email) return email;\n\n let userId = this.userId();\n if (isEmail(userId)) return userId;\n};\n\n/**\n * Get the page fullName. This is `$category $name` if both are present, and\n * just `name` otherwiser.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.fullName = function () {\n let category = this.category();\n let name = this.name();\n return name && category ? category + \" \" + name : name;\n};\n\n/**\n * Get an event name from this page call. If `name` is present, this will be\n * `Viewed $name Page`; otherwise, it will be `Loaded a Page`.\n *\n * @param {string} name - The name of this page.\n * @return {string}\n */\np.event = function (name) {\n return name ? \"Viewed \" + name + \" Page\" : \"Loaded a Page\";\n};\n\n/**\n * Convert this Page to a {@link Track} facade. The inputted `name` will be\n * converted to the Track's event name via {@link Page#event}.\n *\n * @param {string} name\n * @return {Track}\n */\np.track = function (name) {\n let json = this.json();\n json.event = this.event(name);\n json.timestamp = this.timestamp();\n json.properties = this.properties();\n return new Track(json, this.opts);\n};\n","\"use strict\";\n\nimport inherit from \"inherits\";\nimport { Page } from \"./page\";\nimport { Track } from \"./track\";\n\n/**\n * Initialize a new `Screen` facade with a `dictionary` of arguments.\n *\n * Note that this class extends {@link Page}, so its methods are available to\n * instances of this class as well.\n *\n * @param {Object} dictionary - The object to wrap.\n * @param {string} [dictionary.category] - The page category.\n * @param {string} [dictionary.name] - The page name.\n * @param {string} [dictionary.properties] - The page properties.\n * @param {Object} opts - Options about what kind of Facade to create.\n *\n * @augments Page\n */\nexport function Screen(dictionary, opts) {\n Page.call(this, dictionary, opts);\n}\n\ninherit(Screen, Page);\n\n/**\n * Return the type of facade this is. This will always return `\"screen\"`.\n *\n * @return {string}\n */\nScreen.prototype.action = function () {\n return \"screen\";\n};\n\n/**\n * An alias for {@link Screen#action}.\n *\n * @function\n * @return {string}\n */\nScreen.prototype.type = Screen.prototype.action;\n\n/**\n * Get an event name from this screen call. If `name` is present, this will be\n * `Viewed $name Screen`; otherwise, it will be `Loaded a Screen`.\n *\n * @param {string} name - The name of this screen.\n * @return {string}\n */\nScreen.prototype.event = function (name) {\n return name ? \"Viewed \" + name + \" Screen\" : \"Loaded a Screen\";\n};\n\n/**\n * Convert this Screen to a {@link Track} facade. The inputted `name` will be\n * converted to the Track's event name via {@link Screen#event}.\n *\n * @param {string} name\n * @return {Track}\n */\nScreen.prototype.track = function (name) {\n let json = this.json();\n json.event = this.event(name);\n json.timestamp = this.timestamp();\n json.properties = this.properties();\n return new Track(json, this.opts);\n};\n","\"use strict\";\n\nimport inherit from \"inherits\";\nimport { Facade } from \"./facade\";\nimport { Identify } from \"./identify\";\nimport isEmail from \"./is-email\";\nimport get from \"obj-case\";\n\n/**\n * Initialize a new `Track` facade with a `dictionary` of arguments.\n *\n * @param {Object} dictionary - The object to wrap.\n * @param {string} [dictionary.event] - The name of the event being tracked.\n * @param {string} [dictionary.userId] - The ID of the user being tracked.\n * @param {string} [dictionary.anonymousId] - The anonymous ID of the user.\n * @param {string} [dictionary.properties] - Properties of the track event.\n * @param {Object} opts - Options about what kind of Facade to create.\n *\n * @augments Facade\n */\nexport function Track(dictionary, opts) {\n Facade.call(this, dictionary, opts);\n}\n\ninherit(Track, Facade);\n\nlet t = Track.prototype;\n\n/**\n * Return the type of facade this is. This will always return `\"track\"`.\n *\n * @return {string}\n */\nt.action = function () {\n return \"track\";\n};\n\n/**\n * An alias for {@link Track#action}.\n *\n * @function\n * @return {string}\n */\nt.type = t.action;\n\n/**\n * Get the event name from `event`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.event = Facade.field(\"event\");\n\n/**\n * Get the event value, usually the monetary value, from `properties.value`.\n *\n * This *should* be a number, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {number}\n */\nt.value = Facade.proxy(\"properties.value\");\n\n/**\n * Get the event cateogry from `properties.category`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.category = Facade.proxy(\"properties.category\");\n\n/**\n * Get the event ID from `properties.id`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.id = Facade.proxy(\"properties.id\");\n\n/**\n * Get the product ID from `properties.productId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.productId = function () {\n return (\n this.proxy(\"properties.product_id\") || this.proxy(\"properties.productId\")\n );\n};\n\n/**\n * Get the promotion ID from `properties.promotionId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.promotionId = function () {\n return (\n this.proxy(\"properties.promotion_id\") ||\n this.proxy(\"properties.promotionId\")\n );\n};\n\n/**\n * Get the cart ID from `properties.cartId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.cartId = function () {\n return this.proxy(\"properties.cart_id\") || this.proxy(\"properties.cartId\");\n};\n\n/**\n * Get the checkout ID from `properties.checkoutId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.checkoutId = function () {\n return (\n this.proxy(\"properties.checkout_id\") || this.proxy(\"properties.checkoutId\")\n );\n};\n\n/**\n * Get the payment ID from `properties.paymentId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.paymentId = function () {\n return (\n this.proxy(\"properties.payment_id\") || this.proxy(\"properties.paymentId\")\n );\n};\n\n/**\n * Get the coupon ID from `properties.couponId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.couponId = function () {\n return (\n this.proxy(\"properties.coupon_id\") || this.proxy(\"properties.couponId\")\n );\n};\n\n/**\n * Get the wishlist ID from `properties.wishlistId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.wishlistId = function () {\n return (\n this.proxy(\"properties.wishlist_id\") || this.proxy(\"properties.wishlistId\")\n );\n};\n\n/**\n * Get the review ID from `properties.reviewId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.reviewId = function () {\n return (\n this.proxy(\"properties.review_id\") || this.proxy(\"properties.reviewId\")\n );\n};\n\n/**\n * Get the order ID from `properties.id` or `properties.orderId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.orderId = function () {\n // doesn't follow above convention since this fallback order was how it used to be\n return (\n this.proxy(\"properties.id\") ||\n this.proxy(\"properties.order_id\") ||\n this.proxy(\"properties.orderId\")\n );\n};\n\n/**\n * Get the SKU from `properties.sku`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.sku = Facade.proxy(\"properties.sku\");\n\n/**\n * Get the amount of tax for this purchase from `properties.tax`.\n *\n * This *should* be a number, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {number}\n */\nt.tax = Facade.proxy(\"properties.tax\");\n\n/**\n * Get the name of this event from `properties.name`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.name = Facade.proxy(\"properties.name\");\n\n/**\n * Get the price of this purchase from `properties.price`.\n *\n * This *should* be a number, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {number}\n */\nt.price = Facade.proxy(\"properties.price\");\n\n/**\n * Get the total for this purchase from `properties.total`.\n *\n * This *should* be a number, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {number}\n */\nt.total = Facade.proxy(\"properties.total\");\n\n/**\n * Whether this is a repeat purchase from `properties.repeat`.\n *\n * This *should* be a boolean, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {boolean}\n */\nt.repeat = Facade.proxy(\"properties.repeat\");\n\n/**\n * Get the coupon for this purchase from `properties.coupon`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.coupon = Facade.proxy(\"properties.coupon\");\n\n/**\n * Get the shipping for this purchase from `properties.shipping`.\n *\n * This *should* be a number, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {number}\n */\nt.shipping = Facade.proxy(\"properties.shipping\");\n\n/**\n * Get the discount for this purchase from `properties.discount`.\n *\n * This *should* be a number, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {number}\n */\nt.discount = Facade.proxy(\"properties.discount\");\n\n/**\n * Get the shipping method for this purchase from `properties.shippingMethod`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.shippingMethod = function () {\n return (\n this.proxy(\"properties.shipping_method\") ||\n this.proxy(\"properties.shippingMethod\")\n );\n};\n\n/**\n * Get the payment method for this purchase from `properties.paymentMethod`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.paymentMethod = function () {\n return (\n this.proxy(\"properties.payment_method\") ||\n this.proxy(\"properties.paymentMethod\")\n );\n};\n\n/**\n * Get a description for this event from `properties.description`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.description = Facade.proxy(\"properties.description\");\n\n/**\n * Get a plan, as in the plan the user is on, for this event from\n * `properties.plan`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.plan = Facade.proxy(\"properties.plan\");\n\n/**\n * Get the subtotal for this purchase from `properties.subtotal`.\n *\n * If `properties.subtotal` isn't available, then fall back to computing the\n * total from `properties.total` or `properties.revenue`, and then subtracting\n * tax, shipping, and discounts.\n *\n * If neither subtotal, total, nor revenue are available, then return 0.\n *\n * @return {number}\n */\nt.subtotal = function () {\n let subtotal = get(this.properties(), \"subtotal\");\n let total = this.total() || this.revenue();\n\n if (subtotal) return subtotal;\n if (!total) return 0;\n\n if (this.total()) {\n let n = this.tax();\n if (n) total -= n;\n n = this.shipping();\n if (n) total -= n;\n n = this.discount();\n if (n) total += n;\n }\n\n return total;\n};\n\n/**\n * Get the products for this event from `properties.products` if it's an\n * array, falling back to an empty array.\n *\n * @return {Array}\n */\nt.products = function () {\n let props = this.properties();\n let products = get(props, \"products\");\n if (Array.isArray(products)) {\n return products.filter(item => item !== null)\n }\n return [];\n};\n\n/**\n * Get the quantity for this event from `properties.quantity`, falling back to\n * a quantity of one.\n *\n * @return {number}\n */\nt.quantity = function () {\n let props = this.obj.properties || {};\n return props.quantity || 1;\n};\n\n/**\n * Get the currency for this event from `properties.currency`, falling back to\n * \"USD\".\n *\n * @return {string}\n */\nt.currency = function () {\n let props = this.obj.properties || {};\n return props.currency || \"USD\";\n};\n\n/**\n * Get the referrer for this event from `context.referrer.url`,\n * `context.page.referrer`, or `properties.referrer`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.referrer = function () {\n // TODO re-examine whether this function is necessary\n return (\n this.proxy(\"context.referrer.url\") ||\n this.proxy(\"context.page.referrer\") ||\n this.proxy(\"properties.referrer\")\n );\n};\n\n/**\n * Get the query for this event from `options.query`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string|object}\n */\nt.query = Facade.proxy(\"options.query\");\n\n/**\n * Get the page's properties. This is identical to how {@link Facade#traits}\n * works, except it looks at `properties.*` instead of `options.traits.*`.\n *\n * Properties are gotten from `properties`.\n *\n * The parameter `aliases` is meant to transform keys in `properties` into new\n * keys. Each alias like `{ \"xxx\": \"yyy\" }` will take whatever is at `xxx` in\n * the traits, and move it to `yyy`. If `xxx` is a method of this facade, it'll\n * be called as a function instead of treated as a key into the traits.\n *\n * @example\n * let obj = { properties: { foo: \"bar\" }, anonymousId: \"xxx\" }\n * let track = new Track(obj)\n *\n * track.traits() // { \"foo\": \"bar\" }\n * track.traits({ \"foo\": \"asdf\" }) // { \"asdf\": \"bar\" }\n * track.traits({ \"sessionId\": \"rofl\" }) // { \"rofl\": \"xxx\" }\n *\n * @param {Object} aliases - A mapping from keys to the new keys they should be\n * transformed to.\n * @return {Object}\n */\nt.properties = function (aliases) {\n let ret = this.field(\"properties\") || {};\n aliases = aliases || {};\n\n for (const alias in aliases) {\n if (Object.prototype.hasOwnProperty.call(aliases, alias)) {\n const value = this[alias] == null\n ? this.proxy(\"properties.\" + alias)\n : this[alias]();\n if (value == null) continue;\n ret[aliases[alias]] = value;\n delete ret[alias];\n }\n }\n\n return ret;\n};\n\n/**\n * Get the username of the user for this event from `traits.username`,\n * `properties.username`, `userId`, or `anonymousId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string|undefined}\n */\nt.username = function () {\n return (\n this.proxy(\"traits.username\") ||\n this.proxy(\"properties.username\") ||\n this.userId() ||\n this.sessionId()\n );\n};\n\n/**\n * Get the email of the user for this event from `trais.email`,\n * `properties.email`, or `options.traits.email`, falling back to `userId` if\n * it looks like a valid email.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string|undefined}\n */\nt.email = function () {\n let email =\n this.proxy(\"traits.email\") ||\n this.proxy(\"properties.email\") ||\n this.proxy(\"options.traits.email\");\n if (email) return email;\n\n let userId = this.userId();\n if (isEmail(userId)) return userId;\n};\n\n/**\n * Get the revenue for this event.\n *\n * If this is an \"Order Completed\" event, this will be the `properties.total`\n * falling back to the `properties.revenue`. For all other events, this is\n * simply taken from `properties.revenue`.\n *\n * If there are dollar signs in these properties, they will be removed. The\n * result will be parsed into a number.\n *\n * @return {number}\n */\nt.revenue = function () {\n let revenue = this.proxy(\"properties.revenue\");\n let event = this.event();\n let orderCompletedRegExp = /^[ _]?completed[ _]?order[ _]?|^[ _]?order[ _]?completed[ _]?$/i;\n\n // it's always revenue, unless it's called during an order completion.\n if (!revenue && event && event.match(orderCompletedRegExp)) {\n revenue = this.proxy(\"properties.total\");\n }\n\n return currency(revenue);\n};\n\n/**\n * Get the revenue for this event in \"cents\" -- in other words, multiply the\n * {@link Track#revenue} by 100, or return 0 if there isn't a numerical revenue\n * for this event.\n *\n * @return {number}\n */\nt.cents = function () {\n let revenue = this.revenue();\n return typeof revenue !== \"number\" ? this.value() || 0 : revenue * 100;\n};\n\n/**\n * Convert this event into an {@link Identify} facade.\n *\n * This works by taking this event's underlying object and creating an Identify\n * from it. This event's traits, taken from `options.traits`, will be used as\n * the Identify's traits.\n *\n * @return {Identify}\n */\nt.identify = function () {\n // TODO: remove me.\n let json = this.json();\n json.traits = this.traits();\n return new Identify(json, this.opts);\n};\n\n/**\n * Get float from currency value.\n *\n * @ignore\n * @param {*} val\n * @return {number}\n */\nfunction currency(val) {\n if (!val) return;\n if (typeof val === \"number\") {\n return val;\n }\n if (typeof val !== \"string\") {\n return;\n }\n\n val = val.replace(/\\$/g, \"\");\n val = parseFloat(val);\n\n if (!isNaN(val)) {\n return val;\n }\n}\n","'use strict';\n\nvar isodate = require('@segment/isodate');\n\n/**\n * Expose `traverse`.\n */\nmodule.exports = traverse;\n\n/**\n * Recursively traverse an object or array, and convert\n * all ISO date strings parse into Date objects.\n *\n * @param {Object} input - object, array, or string to convert\n * @param {Boolean} strict - only convert strings with year, month, and date\n * @return {Object}\n */\nfunction traverse(input, strict) {\n if (strict === undefined) strict = true;\n if (input && typeof input === 'object') {\n return traverseObject(input, strict);\n } else if (Array.isArray(input)) {\n return traverseArray(input, strict);\n } else if (isodate.is(input, strict)) {\n return isodate.parse(input);\n }\n return input;\n}\n\n/**\n * Object traverser helper function.\n *\n * @param {Object} obj - object to traverse\n * @param {Boolean} strict - only convert strings with year, month, and date\n * @return {Object}\n */\nfunction traverseObject(obj, strict) {\n Object.keys(obj).forEach(function(key) {\n obj[key] = traverse(obj[key], strict);\n });\n return obj;\n}\n\n/**\n * Array traverser helper function\n *\n * @param {Array} arr - array to traverse\n * @param {Boolean} strict - only convert strings with year, month, and date\n * @return {Array}\n */\nfunction traverseArray(arr, strict) {\n arr.forEach(function(value, index) {\n arr[index] = traverse(value, strict);\n });\n return arr;\n}\n","'use strict';\n\n/**\n * Matcher, slightly modified from:\n *\n * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js\n */\n\nvar matcher = /^(\\d{4})(?:-?(\\d{2})(?:-?(\\d{2}))?)?(?:([ T])(\\d{2}):?(\\d{2})(?::?(\\d{2})(?:[,\\.](\\d{1,}))?)?(?:(Z)|([+\\-])(\\d{2})(?::?(\\d{2}))?)?)?$/;\n\n/**\n * Convert an ISO date string to a date. Fallback to native `Date.parse`.\n *\n * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js\n *\n * @param {String} iso\n * @return {Date}\n */\n\nexports.parse = function(iso) {\n var numericKeys = [1, 5, 6, 7, 11, 12];\n var arr = matcher.exec(iso);\n var offset = 0;\n\n // fallback to native parsing\n if (!arr) {\n return new Date(iso);\n }\n\n /* eslint-disable no-cond-assign */\n // remove undefined values\n for (var i = 0, val; val = numericKeys[i]; i++) {\n arr[val] = parseInt(arr[val], 10) || 0;\n }\n /* eslint-enable no-cond-assign */\n\n // allow undefined days and months\n arr[2] = parseInt(arr[2], 10) || 1;\n arr[3] = parseInt(arr[3], 10) || 1;\n\n // month is 0-11\n arr[2]--;\n\n // allow abitrary sub-second precision\n arr[8] = arr[8] ? (arr[8] + '00').substring(0, 3) : 0;\n\n // apply timezone if one exists\n if (arr[4] === ' ') {\n offset = new Date().getTimezoneOffset();\n } else if (arr[9] !== 'Z' && arr[10]) {\n offset = arr[11] * 60 + arr[12];\n if (arr[10] === '+') {\n offset = 0 - offset;\n }\n }\n\n var millis = Date.UTC(arr[1], arr[2], arr[3], arr[5], arr[6] + offset, arr[7], arr[8]);\n return new Date(millis);\n};\n\n\n/**\n * Checks whether a `string` is an ISO date string. `strict` mode requires that\n * the date string at least have a year, month and date.\n *\n * @param {String} string\n * @param {Boolean} strict\n * @return {Boolean}\n */\n\nexports.is = function(string, strict) {\n if (typeof string !== 'string') {\n return false;\n }\n if (strict && (/^\\d{4}-\\d{2}-\\d{2}/).test(string) === false) {\n return false;\n }\n return matcher.test(string);\n};\n","\"use strict\";\n/* eslint-disable */\n/* tslint:disable */\n/*\n * ---------------------------------------------------------------\n * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##\n * ## ##\n * ## AUTHOR: acacode ##\n * ## SOURCE: https://github.com/acacode/swagger-typescript-api ##\n * ---------------------------------------------------------------\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Api = exports.HttpClient = exports.ContentType = void 0;\nvar ContentType;\n(function (ContentType) {\n ContentType[\"Json\"] = \"application/json\";\n ContentType[\"FormData\"] = \"multipart/form-data\";\n ContentType[\"UrlEncoded\"] = \"application/x-www-form-urlencoded\";\n ContentType[\"Text\"] = \"text/plain\";\n})(ContentType || (exports.ContentType = ContentType = {}));\nclass HttpClient {\n baseUrl = 'https://api.vapi.ai';\n securityData = null;\n securityWorker;\n abortControllers = new Map();\n customFetch = (...fetchParams) => fetch(...fetchParams);\n baseApiParams = {\n credentials: 'same-origin',\n headers: {},\n redirect: 'follow',\n referrerPolicy: 'no-referrer',\n };\n constructor(apiConfig = {}) {\n Object.assign(this, apiConfig);\n }\n setSecurityData = (data) => {\n this.securityData = data;\n };\n encodeQueryParam(key, value) {\n const encodedKey = encodeURIComponent(key);\n return `${encodedKey}=${encodeURIComponent(typeof value === 'number' ? value : `${value}`)}`;\n }\n addQueryParam(query, key) {\n return this.encodeQueryParam(key, query[key]);\n }\n addArrayQueryParam(query, key) {\n const value = query[key];\n return value.map((v) => this.encodeQueryParam(key, v)).join('&');\n }\n toQueryString(rawQuery) {\n const query = rawQuery || {};\n const keys = Object.keys(query).filter((key) => 'undefined' !== typeof query[key]);\n return keys\n .map((key) => Array.isArray(query[key])\n ? this.addArrayQueryParam(query, key)\n : this.addQueryParam(query, key))\n .join('&');\n }\n addQueryParams(rawQuery) {\n const queryString = this.toQueryString(rawQuery);\n return queryString ? `?${queryString}` : '';\n }\n contentFormatters = {\n [ContentType.Json]: (input) => input !== null && (typeof input === 'object' || typeof input === 'string')\n ? JSON.stringify(input)\n : input,\n [ContentType.Text]: (input) => input !== null && typeof input !== 'string' ? JSON.stringify(input) : input,\n [ContentType.FormData]: (input) => Object.keys(input || {}).reduce((formData, key) => {\n const property = input[key];\n formData.append(key, property instanceof Blob\n ? property\n : typeof property === 'object' && property !== null\n ? JSON.stringify(property)\n : `${property}`);\n return formData;\n }, new FormData()),\n [ContentType.UrlEncoded]: (input) => this.toQueryString(input),\n };\n mergeRequestParams(params1, params2) {\n return {\n ...this.baseApiParams,\n ...params1,\n ...(params2 || {}),\n headers: {\n ...(this.baseApiParams.headers || {}),\n ...(params1.headers || {}),\n ...((params2 && params2.headers) || {}),\n },\n };\n }\n createAbortSignal = (cancelToken) => {\n if (this.abortControllers.has(cancelToken)) {\n const abortController = this.abortControllers.get(cancelToken);\n if (abortController) {\n return abortController.signal;\n }\n return void 0;\n }\n const abortController = new AbortController();\n this.abortControllers.set(cancelToken, abortController);\n return abortController.signal;\n };\n abortRequest = (cancelToken) => {\n const abortController = this.abortControllers.get(cancelToken);\n if (abortController) {\n abortController.abort();\n this.abortControllers.delete(cancelToken);\n }\n };\n request = async ({ body, secure, path, type, query, format, baseUrl, cancelToken, ...params }) => {\n const secureParams = ((typeof secure === 'boolean' ? secure : this.baseApiParams.secure) &&\n this.securityWorker &&\n (await this.securityWorker(this.securityData))) ||\n {};\n const requestParams = this.mergeRequestParams(params, secureParams);\n const queryString = query && this.toQueryString(query);\n const payloadFormatter = this.contentFormatters[type || ContentType.Json];\n const responseFormat = format || requestParams.format;\n return this.customFetch(`${baseUrl || this.baseUrl || ''}${path}${queryString ? `?${queryString}` : ''}`, {\n ...requestParams,\n headers: {\n ...(requestParams.headers || {}),\n ...(type && type !== ContentType.FormData ? { 'Content-Type': type } : {}),\n },\n signal: (cancelToken ? this.createAbortSignal(cancelToken) : requestParams.signal) || null,\n body: typeof body === 'undefined' || body === null ? null : payloadFormatter(body),\n }).then(async (response) => {\n const r = response;\n r.data = null;\n r.error = null;\n const data = !responseFormat\n ? r\n : await response[responseFormat]()\n .then((data) => {\n if (r.ok) {\n r.data = data;\n }\n else {\n r.error = data;\n }\n return r;\n })\n .catch((e) => {\n r.error = e;\n return r;\n });\n if (cancelToken) {\n this.abortControllers.delete(cancelToken);\n }\n if (!response.ok)\n throw data;\n return data;\n });\n };\n}\nexports.HttpClient = HttpClient;\n/**\n * @title Vapi API\n * @version 1.0\n * @baseUrl https://api.vapi.ai\n * @contact\n *\n * Voice AI for developers.\n */\nclass Api extends HttpClient {\n call = {\n /**\n * No description\n *\n * @tags Calls\n * @name CallControllerCreate\n * @summary Create Call\n * @request POST:/call\n * @secure\n */\n callControllerCreate: (data, params = {}) => this.request({\n path: `/call`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Calls\n * @name CallControllerFindAll\n * @summary List Calls\n * @request GET:/call\n * @secure\n */\n callControllerFindAll: (query, params = {}) => this.request({\n path: `/call`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Calls\n * @name CallControllerFindOne\n * @summary Get Call\n * @request GET:/call/{id}\n * @secure\n */\n callControllerFindOne: (id, params = {}) => this.request({\n path: `/call/${id}`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Calls\n * @name CallControllerUpdate\n * @summary Update Call\n * @request PATCH:/call/{id}\n * @secure\n */\n callControllerUpdate: (id, data, params = {}) => this.request({\n path: `/call/${id}`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Calls\n * @name CallControllerDeleteCallData\n * @summary Delete Call Data\n * @request DELETE:/call/{id}\n * @secure\n */\n callControllerDeleteCallData: (id, params = {}) => this.request({\n path: `/call/${id}`,\n method: 'DELETE',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Calls\n * @name CallControllerCreatePhoneCall\n * @summary Create Phone Call\n * @request POST:/call/phone\n * @deprecated\n * @secure\n */\n callControllerCreatePhoneCall: (data, params = {}) => this.request({\n path: `/call/phone`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Calls\n * @name CallControllerCreateWebCall\n * @summary Create Web Call\n * @request POST:/call/web\n * @secure\n */\n callControllerCreateWebCall: (data, params = {}) => this.request({\n path: `/call/web`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n };\n v2 = {\n /**\n * No description\n *\n * @tags Calls\n * @name CallControllerFindAllPaginated\n * @summary List Calls\n * @request GET:/v2/call\n * @secure\n */\n callControllerFindAllPaginated: (query, params = {}) => this.request({\n path: `/v2/call`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Calls\n * @name CallControllerFindAllMetadataPaginated\n * @summary List Call Metadata\n * @request GET:/v2/call/metadata\n * @secure\n */\n callControllerFindAllMetadataPaginated: (query, params = {}) => this.request({\n path: `/v2/call/metadata`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Assistants\n * @name AssistantControllerFindAllPaginated\n * @summary List Assistants with pagination\n * @request GET:/v2/assistant\n * @secure\n */\n assistantControllerFindAllPaginated: (query, params = {}) => this.request({\n path: `/v2/assistant`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Phone Numbers\n * @name PhoneNumberControllerFindAllPaginated\n * @summary List Phone Numbers\n * @request GET:/v2/phone-number\n * @secure\n */\n phoneNumberControllerFindAllPaginated: (query, params = {}) => this.request({\n path: `/v2/phone-number`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n };\n chat = {\n /**\n * No description\n *\n * @tags Chat\n * @name ChatController\n * @summary Chat with Assistant\n * @request POST:/chat\n * @deprecated\n * @secure\n */\n chatController: (params = {}) => this.request({\n path: `/chat`,\n method: 'POST',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Chat\n * @name ChatControllerChatCompletions\n * @summary Chat with a Workflow\n * @request POST:/chat/completions\n * @secure\n */\n chatControllerChatCompletions: (data, params = {}) => this.request({\n path: `/chat/completions`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n };\n assistant = {\n /**\n * No description\n *\n * @tags Assistants\n * @name AssistantControllerCreate\n * @summary Create Assistant\n * @request POST:/assistant\n * @secure\n */\n assistantControllerCreate: (data, params = {}) => this.request({\n path: `/assistant`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Assistants\n * @name AssistantControllerFindAll\n * @summary List Assistants\n * @request GET:/assistant\n * @secure\n */\n assistantControllerFindAll: (query, params = {}) => this.request({\n path: `/assistant`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Assistants\n * @name AssistantControllerFindOne\n * @summary Get Assistant\n * @request GET:/assistant/{id}\n * @secure\n */\n assistantControllerFindOne: (id, params = {}) => this.request({\n path: `/assistant/${id}`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Assistants\n * @name AssistantControllerUpdate\n * @summary Update Assistant\n * @request PATCH:/assistant/{id}\n * @secure\n */\n assistantControllerUpdate: (id, data, params = {}) => this.request({\n path: `/assistant/${id}`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Assistants\n * @name AssistantControllerReplace\n * @summary Replace Assistant\n * @request PUT:/assistant/{id}\n * @secure\n */\n assistantControllerReplace: (id, data, params = {}) => this.request({\n path: `/assistant/${id}`,\n method: 'PUT',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Assistants\n * @name AssistantControllerRemove\n * @summary Delete Assistant\n * @request DELETE:/assistant/{id}\n * @secure\n */\n assistantControllerRemove: (id, params = {}) => this.request({\n path: `/assistant/${id}`,\n method: 'DELETE',\n secure: true,\n format: 'json',\n ...params,\n }),\n };\n phoneNumber = {\n /**\n * @description Use POST /phone-number instead.\n *\n * @tags Phone Numbers\n * @name PhoneNumberControllerImportTwilio\n * @summary Import Twilio Number\n * @request POST:/phone-number/import/twilio\n * @deprecated\n * @secure\n */\n phoneNumberControllerImportTwilio: (data, params = {}) => this.request({\n path: `/phone-number/import/twilio`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * @description Use POST /phone-number instead.\n *\n * @tags Phone Numbers\n * @name PhoneNumberControllerImportVonage\n * @summary Import Vonage Number\n * @request POST:/phone-number/import/vonage\n * @deprecated\n * @secure\n */\n phoneNumberControllerImportVonage: (data, params = {}) => this.request({\n path: `/phone-number/import/vonage`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Phone Numbers\n * @name PhoneNumberControllerCreate\n * @summary Create Phone Number\n * @request POST:/phone-number\n * @secure\n */\n phoneNumberControllerCreate: (data, params = {}) => this.request({\n path: `/phone-number`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Phone Numbers\n * @name PhoneNumberControllerFindAll\n * @summary List Phone Numbers\n * @request GET:/phone-number\n * @secure\n */\n phoneNumberControllerFindAll: (query, params = {}) => this.request({\n path: `/phone-number`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Phone Numbers\n * @name PhoneNumberControllerFindOne\n * @summary Get Phone Number\n * @request GET:/phone-number/{id}\n * @secure\n */\n phoneNumberControllerFindOne: (id, params = {}) => this.request({\n path: `/phone-number/${id}`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Phone Numbers\n * @name PhoneNumberControllerUpdate\n * @summary Update Phone Number\n * @request PATCH:/phone-number/{id}\n * @secure\n */\n phoneNumberControllerUpdate: (id, data, params = {}) => this.request({\n path: `/phone-number/${id}`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Phone Numbers\n * @name PhoneNumberControllerRemove\n * @summary Delete Phone Number\n * @request DELETE:/phone-number/{id}\n * @secure\n */\n phoneNumberControllerRemove: (id, params = {}) => this.request({\n path: `/phone-number/${id}`,\n method: 'DELETE',\n secure: true,\n format: 'json',\n ...params,\n }),\n };\n tool = {\n /**\n * No description\n *\n * @tags Tools\n * @name ToolControllerCreate\n * @summary Create Tool\n * @request POST:/tool\n * @secure\n */\n toolControllerCreate: (data, params = {}) => this.request({\n path: `/tool`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Tools\n * @name ToolControllerFindAll\n * @summary List Tools\n * @request GET:/tool\n * @secure\n */\n toolControllerFindAll: (query, params = {}) => this.request({\n path: `/tool`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Tools\n * @name ToolControllerFindOne\n * @summary Get Tool\n * @request GET:/tool/{id}\n * @secure\n */\n toolControllerFindOne: (id, params = {}) => this.request({\n path: `/tool/${id}`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Tools\n * @name ToolControllerUpdate\n * @summary Update Tool\n * @request PATCH:/tool/{id}\n * @secure\n */\n toolControllerUpdate: (id, data, params = {}) => this.request({\n path: `/tool/${id}`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Tools\n * @name ToolControllerRemove\n * @summary Delete Tool\n * @request DELETE:/tool/{id}\n * @secure\n */\n toolControllerRemove: (id, params = {}) => this.request({\n path: `/tool/${id}`,\n method: 'DELETE',\n secure: true,\n format: 'json',\n ...params,\n }),\n };\n file = {\n /**\n * @description Use POST /file instead.\n *\n * @tags Files\n * @name FileControllerCreateDeprecated\n * @summary Upload File\n * @request POST:/file/upload\n * @deprecated\n * @secure\n */\n fileControllerCreateDeprecated: (data, params = {}) => this.request({\n path: `/file/upload`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.FormData,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Files\n * @name FileControllerCreate\n * @summary Upload File\n * @request POST:/file\n * @secure\n */\n fileControllerCreate: (data, params = {}) => this.request({\n path: `/file`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.FormData,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Files\n * @name FileControllerFindAll\n * @summary List Files\n * @request GET:/file\n * @secure\n */\n fileControllerFindAll: (params = {}) => this.request({\n path: `/file`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Files\n * @name FileControllerFindOne\n * @summary Get File\n * @request GET:/file/{id}\n * @secure\n */\n fileControllerFindOne: (id, params = {}) => this.request({\n path: `/file/${id}`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Files\n * @name FileControllerUpdate\n * @summary Update File\n * @request PATCH:/file/{id}\n * @secure\n */\n fileControllerUpdate: (id, data, params = {}) => this.request({\n path: `/file/${id}`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Files\n * @name FileControllerRemove\n * @summary Delete File\n * @request DELETE:/file/{id}\n * @secure\n */\n fileControllerRemove: (id, params = {}) => this.request({\n path: `/file/${id}`,\n method: 'DELETE',\n secure: true,\n format: 'json',\n ...params,\n }),\n };\n knowledgeBase = {\n /**\n * No description\n *\n * @tags Knowledge Base\n * @name KnowledgeBaseControllerCreate\n * @summary Create Knowledge Base\n * @request POST:/knowledge-base\n * @secure\n */\n knowledgeBaseControllerCreate: (data, params = {}) => this.request({\n path: `/knowledge-base`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Knowledge Base\n * @name KnowledgeBaseControllerFindAll\n * @summary List Knowledge Bases\n * @request GET:/knowledge-base\n * @secure\n */\n knowledgeBaseControllerFindAll: (query, params = {}) => this.request({\n path: `/knowledge-base`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Knowledge Base\n * @name KnowledgeBaseControllerFindOne\n * @summary Get Knowledge Base\n * @request GET:/knowledge-base/{id}\n * @secure\n */\n knowledgeBaseControllerFindOne: (id, params = {}) => this.request({\n path: `/knowledge-base/${id}`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Knowledge Base\n * @name KnowledgeBaseControllerUpdate\n * @summary Update Knowledge Base\n * @request PATCH:/knowledge-base/{id}\n * @secure\n */\n knowledgeBaseControllerUpdate: (id, data, params = {}) => this.request({\n path: `/knowledge-base/${id}`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Knowledge Base\n * @name KnowledgeBaseControllerRemove\n * @summary Delete Knowledge Base\n * @request DELETE:/knowledge-base/{id}\n * @secure\n */\n knowledgeBaseControllerRemove: (id, params = {}) => this.request({\n path: `/knowledge-base/${id}`,\n method: 'DELETE',\n secure: true,\n format: 'json',\n ...params,\n }),\n };\n workflow = {\n /**\n * No description\n *\n * @tags Workflow\n * @name WorkflowControllerFindAll\n * @summary Get Workflows\n * @request GET:/workflow\n * @secure\n */\n workflowControllerFindAll: (params = {}) => this.request({\n path: `/workflow`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Workflow\n * @name WorkflowControllerCreate\n * @summary Create Workflow\n * @request POST:/workflow\n * @secure\n */\n workflowControllerCreate: (data, params = {}) => this.request({\n path: `/workflow`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Workflow\n * @name WorkflowControllerFindOne\n * @summary Get Workflow\n * @request GET:/workflow/{id}\n * @secure\n */\n workflowControllerFindOne: (id, params = {}) => this.request({\n path: `/workflow/${id}`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Workflow\n * @name WorkflowControllerDelete\n * @summary Delete Workflow\n * @request DELETE:/workflow/{id}\n * @secure\n */\n workflowControllerDelete: (id, params = {}) => this.request({\n path: `/workflow/${id}`,\n method: 'DELETE',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Workflow\n * @name WorkflowControllerUpdate\n * @summary Update Workflow\n * @request PATCH:/workflow/{id}\n * @secure\n */\n workflowControllerUpdate: (id, data, params = {}) => this.request({\n path: `/workflow/${id}`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n };\n squad = {\n /**\n * No description\n *\n * @tags Squads\n * @name SquadControllerCreate\n * @summary Create Squad\n * @request POST:/squad\n * @secure\n */\n squadControllerCreate: (data, params = {}) => this.request({\n path: `/squad`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Squads\n * @name SquadControllerFindAll\n * @summary List Squads\n * @request GET:/squad\n * @secure\n */\n squadControllerFindAll: (query, params = {}) => this.request({\n path: `/squad`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Squads\n * @name SquadControllerFindOne\n * @summary Get Squad\n * @request GET:/squad/{id}\n * @secure\n */\n squadControllerFindOne: (id, params = {}) => this.request({\n path: `/squad/${id}`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Squads\n * @name SquadControllerUpdate\n * @summary Update Squad\n * @request PATCH:/squad/{id}\n * @secure\n */\n squadControllerUpdate: (id, data, params = {}) => this.request({\n path: `/squad/${id}`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Squads\n * @name SquadControllerRemove\n * @summary Delete Squad\n * @request DELETE:/squad/{id}\n * @secure\n */\n squadControllerRemove: (id, params = {}) => this.request({\n path: `/squad/${id}`,\n method: 'DELETE',\n secure: true,\n format: 'json',\n ...params,\n }),\n };\n testSuite = {\n /**\n * No description\n *\n * @tags Test Suites\n * @name TestSuiteControllerFindAllPaginated\n * @summary List Test Suites\n * @request GET:/test-suite\n * @secure\n */\n testSuiteControllerFindAllPaginated: (query, params = {}) => this.request({\n path: `/test-suite`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Test Suites\n * @name TestSuiteControllerCreate\n * @summary Create Test Suite\n * @request POST:/test-suite\n * @secure\n */\n testSuiteControllerCreate: (data, params = {}) => this.request({\n path: `/test-suite`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Test Suites\n * @name TestSuiteControllerFindOne\n * @summary Get Test Suite\n * @request GET:/test-suite/{id}\n * @secure\n */\n testSuiteControllerFindOne: (id, params = {}) => this.request({\n path: `/test-suite/${id}`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Test Suites\n * @name TestSuiteControllerUpdate\n * @summary Update Test Suite\n * @request PATCH:/test-suite/{id}\n * @secure\n */\n testSuiteControllerUpdate: (id, data, params = {}) => this.request({\n path: `/test-suite/${id}`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Test Suites\n * @name TestSuiteControllerRemove\n * @summary Delete Test Suite\n * @request DELETE:/test-suite/{id}\n * @secure\n */\n testSuiteControllerRemove: (id, params = {}) => this.request({\n path: `/test-suite/${id}`,\n method: 'DELETE',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Test Suite Tests\n * @name TestSuiteTestControllerFindAllPaginated\n * @summary List Tests\n * @request GET:/test-suite/{testSuiteId}/test\n * @secure\n */\n testSuiteTestControllerFindAllPaginated: (testSuiteId, query, params = {}) => this.request({\n path: `/test-suite/${testSuiteId}/test`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Test Suite Tests\n * @name TestSuiteTestControllerCreate\n * @summary Create Test\n * @request POST:/test-suite/{testSuiteId}/test\n * @secure\n */\n testSuiteTestControllerCreate: (testSuiteId, data, params = {}) => this.request({\n path: `/test-suite/${testSuiteId}/test`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Test Suite Tests\n * @name TestSuiteTestControllerFindOne\n * @summary Get Test\n * @request GET:/test-suite/{testSuiteId}/test/{id}\n * @secure\n */\n testSuiteTestControllerFindOne: (testSuiteId, id, params = {}) => this.request({\n path: `/test-suite/${testSuiteId}/test/${id}`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Test Suite Tests\n * @name TestSuiteTestControllerUpdate\n * @summary Update Test\n * @request PATCH:/test-suite/{testSuiteId}/test/{id}\n * @secure\n */\n testSuiteTestControllerUpdate: (testSuiteId, id, data, params = {}) => this.request({\n path: `/test-suite/${testSuiteId}/test/${id}`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Test Suite Tests\n * @name TestSuiteTestControllerRemove\n * @summary Delete Test\n * @request DELETE:/test-suite/{testSuiteId}/test/{id}\n * @secure\n */\n testSuiteTestControllerRemove: (testSuiteId, id, params = {}) => this.request({\n path: `/test-suite/${testSuiteId}/test/${id}`,\n method: 'DELETE',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Test Suite Runs\n * @name TestSuiteRunControllerFindAllPaginated\n * @summary List Test Suite Runs\n * @request GET:/test-suite/{testSuiteId}/run\n * @secure\n */\n testSuiteRunControllerFindAllPaginated: (testSuiteId, query, params = {}) => this.request({\n path: `/test-suite/${testSuiteId}/run`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Test Suite Runs\n * @name TestSuiteRunControllerCreate\n * @summary Create Test Suite Run\n * @request POST:/test-suite/{testSuiteId}/run\n * @secure\n */\n testSuiteRunControllerCreate: (testSuiteId, data, params = {}) => this.request({\n path: `/test-suite/${testSuiteId}/run`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Test Suite Runs\n * @name TestSuiteRunControllerFindOne\n * @summary Get Test Suite Run\n * @request GET:/test-suite/{testSuiteId}/run/{id}\n * @secure\n */\n testSuiteRunControllerFindOne: (testSuiteId, id, params = {}) => this.request({\n path: `/test-suite/${testSuiteId}/run/${id}`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Test Suite Runs\n * @name TestSuiteRunControllerUpdate\n * @summary Update Test Suite Run\n * @request PATCH:/test-suite/{testSuiteId}/run/{id}\n * @secure\n */\n testSuiteRunControllerUpdate: (testSuiteId, id, data, params = {}) => this.request({\n path: `/test-suite/${testSuiteId}/run/${id}`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Test Suite Runs\n * @name TestSuiteRunControllerRemove\n * @summary Delete Test Suite Run\n * @request DELETE:/test-suite/{testSuiteId}/run/{id}\n * @secure\n */\n testSuiteRunControllerRemove: (testSuiteId, id, params = {}) => this.request({\n path: `/test-suite/${testSuiteId}/run/${id}`,\n method: 'DELETE',\n secure: true,\n format: 'json',\n ...params,\n }),\n };\n metrics = {\n /**\n * @description Use GET /metric instead\n *\n * @tags Analytics\n * @name AnalyticsControllerFindAllDeprecated\n * @summary List Billing Metrics\n * @request GET:/metrics\n * @deprecated\n * @secure\n */\n analyticsControllerFindAllDeprecated: (query, params = {}) => this.request({\n path: `/metrics`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n };\n analytics = {\n /**\n * No description\n *\n * @tags Analytics\n * @name AnalyticsControllerQuery\n * @summary Create Analytics Queries\n * @request POST:/analytics\n * @secure\n */\n analyticsControllerQuery: (data, params = {}) => this.request({\n path: `/analytics`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n };\n log = {\n /**\n * No description\n *\n * @tags Logs\n * @name LoggingControllerCallLogsQuery\n * @summary Get Call Logs\n * @request GET:/log\n * @secure\n */\n loggingControllerCallLogsQuery: (query, params = {}) => this.request({\n path: `/log`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Logs\n * @name LoggingControllerCallLogsDeleteQuery\n * @summary Delete Call Logs\n * @request DELETE:/log\n * @secure\n */\n loggingControllerCallLogsDeleteQuery: (query, params = {}) => this.request({\n path: `/log`,\n method: 'DELETE',\n query: query,\n secure: true,\n ...params,\n }),\n };\n logs = {\n /**\n * No description\n *\n * @tags Logs\n * @name LoggingControllerLogsQuery\n * @summary Get Logs\n * @request GET:/logs\n * @deprecated\n * @secure\n */\n loggingControllerLogsQuery: (query, params = {}) => this.request({\n path: `/logs`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Logs\n * @name LoggingControllerLogsDeleteQuery\n * @summary Delete Logs\n * @request DELETE:/logs\n * @deprecated\n * @secure\n */\n loggingControllerLogsDeleteQuery: (query, params = {}) => this.request({\n path: `/logs`,\n method: 'DELETE',\n query: query,\n secure: true,\n ...params,\n }),\n };\n org = {\n /**\n * No description\n *\n * @tags Orgs\n * @name OrgControllerCreate\n * @summary Create Org\n * @request POST:/org\n * @secure\n */\n orgControllerCreate: (data, params = {}) => this.request({\n path: `/org`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Orgs\n * @name OrgControllerFindAll\n * @summary List Orgs\n * @request GET:/org\n * @secure\n */\n orgControllerFindAll: (params = {}) => this.request({\n path: `/org`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Orgs\n * @name OrgControllerFindOne\n * @summary Get Org\n * @request GET:/org/{id}\n * @secure\n */\n orgControllerFindOne: (id, params = {}) => this.request({\n path: `/org/${id}`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Orgs\n * @name OrgControllerUpdate\n * @summary Update Org\n * @request PATCH:/org/{id}\n * @secure\n */\n orgControllerUpdate: (id, data, params = {}) => this.request({\n path: `/org/${id}`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Orgs\n * @name OrgControllerDeleteOrg\n * @summary Delete Org\n * @request DELETE:/org/{id}\n * @secure\n */\n orgControllerDeleteOrg: (id, params = {}) => this.request({\n path: `/org/${id}`,\n method: 'DELETE',\n secure: true,\n ...params,\n }),\n /**\n * No description\n *\n * @tags Orgs\n * @name OrgControllerFindAllUsers\n * @summary List Users\n * @request GET:/org/{id}/user\n * @secure\n */\n orgControllerFindAllUsers: (id, params = {}) => this.request({\n path: `/org/${id}/user`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Orgs\n * @name OrgControllerOrgLeave\n * @summary Leave Org\n * @request DELETE:/org/{id}/leave\n * @secure\n */\n orgControllerOrgLeave: (id, params = {}) => this.request({\n path: `/org/${id}/leave`,\n method: 'DELETE',\n secure: true,\n ...params,\n }),\n /**\n * No description\n *\n * @tags Orgs\n * @name OrgControllerOrgRemoveUser\n * @summary Remove Org Member\n * @request DELETE:/org/{id}/member/{memberId}/leave\n * @secure\n */\n orgControllerOrgRemoveUser: (id, memberId, params = {}) => this.request({\n path: `/org/${id}/member/${memberId}/leave`,\n method: 'DELETE',\n secure: true,\n ...params,\n }),\n /**\n * No description\n *\n * @tags Orgs\n * @name OrgControllerUsersInvite\n * @summary Invite User\n * @request POST:/org/{id}/invite\n * @secure\n */\n orgControllerUsersInvite: (id, data, params = {}) => this.request({\n path: `/org/${id}/invite`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n ...params,\n }),\n /**\n * No description\n *\n * @tags Orgs\n * @name OrgControllerUserUpdate\n * @summary Update User Role\n * @request PATCH:/org/{id}/role\n * @secure\n */\n orgControllerUserUpdate: (id, data, params = {}) => this.request({\n path: `/org/${id}/role`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n ...params,\n }),\n };\n token = {\n /**\n * No description\n *\n * @tags Tokens\n * @name TokenControllerCreate\n * @summary Create Token\n * @request POST:/token\n * @secure\n */\n tokenControllerCreate: (data, params = {}) => this.request({\n path: `/token`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Tokens\n * @name TokenControllerFindAll\n * @summary List Tokens\n * @request GET:/token\n * @secure\n */\n tokenControllerFindAll: (query, params = {}) => this.request({\n path: `/token`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Tokens\n * @name TokenControllerFindOne\n * @summary Get Token\n * @request GET:/token/{id}\n * @secure\n */\n tokenControllerFindOne: (id, params = {}) => this.request({\n path: `/token/${id}`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Tokens\n * @name TokenControllerUpdate\n * @summary Update Token\n * @request PATCH:/token/{id}\n * @secure\n */\n tokenControllerUpdate: (id, data, params = {}) => this.request({\n path: `/token/${id}`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Tokens\n * @name TokenControllerRemove\n * @summary Delete Token\n * @request DELETE:/token/{id}\n * @secure\n */\n tokenControllerRemove: (id, params = {}) => this.request({\n path: `/token/${id}`,\n method: 'DELETE',\n secure: true,\n format: 'json',\n ...params,\n }),\n };\n credential = {\n /**\n * No description\n *\n * @tags Credentials\n * @name CredentialControllerCreate\n * @summary Create Credential\n * @request POST:/credential\n * @secure\n */\n credentialControllerCreate: (data, params = {}) => this.request({\n path: `/credential`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Credentials\n * @name CredentialControllerFindAll\n * @summary List Credentials\n * @request GET:/credential\n * @secure\n */\n credentialControllerFindAll: (query, params = {}) => this.request({\n path: `/credential`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Credentials\n * @name CredentialControllerFindOne\n * @summary Get Credential\n * @request GET:/credential/{id}\n * @secure\n */\n credentialControllerFindOne: (id, params = {}) => this.request({\n path: `/credential/${id}`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Credentials\n * @name CredentialControllerUpdate\n * @summary Update Credential\n * @request PATCH:/credential/{id}\n * @secure\n */\n credentialControllerUpdate: (id, data, params = {}) => this.request({\n path: `/credential/${id}`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Credentials\n * @name CredentialControllerRemove\n * @summary Delete Credential\n * @request DELETE:/credential/{id}\n * @secure\n */\n credentialControllerRemove: (id, params = {}) => this.request({\n path: `/credential/${id}`,\n method: 'DELETE',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Credentials\n * @name CredentialControllerGenerateSession\n * @summary Generate a credential session\n * @request POST:/credential/session\n * @secure\n */\n credentialControllerGenerateSession: (data, params = {}) => this.request({\n path: `/credential/session`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Credentials\n * @name CredentialControllerHandleWebhook\n * @summary Handle credential webhook\n * @request POST:/credential/webhook\n */\n credentialControllerHandleWebhook: (data, params = {}) => this.request({\n path: `/credential/webhook`,\n method: 'POST',\n body: data,\n type: ContentType.Json,\n ...params,\n }),\n /**\n * No description\n *\n * @tags Credentials\n * @name CredentialControllerTriggerCredentialAction\n * @summary Trigger a credential action\n * @request POST:/credential/trigger\n * @secure\n */\n credentialControllerTriggerCredentialAction: (data, params = {}) => this.request({\n path: `/credential/trigger`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n ...params,\n }),\n };\n template = {\n /**\n * No description\n *\n * @tags Templates\n * @name TemplateControllerCreate\n * @summary Create Template\n * @request POST:/template\n * @secure\n */\n templateControllerCreate: (data, params = {}) => this.request({\n path: `/template`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Templates\n * @name TemplateControllerFindAll\n * @summary List Templates\n * @request GET:/template\n * @secure\n */\n templateControllerFindAll: (query, params = {}) => this.request({\n path: `/template`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Templates\n * @name TemplateControllerFindAllPinned\n * @summary List Templates\n * @request GET:/template/pinned\n * @secure\n */\n templateControllerFindAllPinned: (params = {}) => this.request({\n path: `/template/pinned`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Templates\n * @name TemplateControllerFindOne\n * @summary Get Template\n * @request GET:/template/{id}\n * @secure\n */\n templateControllerFindOne: (id, params = {}) => this.request({\n path: `/template/${id}`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Templates\n * @name TemplateControllerUpdate\n * @summary Update Template\n * @request PATCH:/template/{id}\n * @secure\n */\n templateControllerUpdate: (id, data, params = {}) => this.request({\n path: `/template/${id}`,\n method: 'PATCH',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Templates\n * @name TemplateControllerRemove\n * @summary Delete Template\n * @request DELETE:/template/{id}\n * @secure\n */\n templateControllerRemove: (id, params = {}) => this.request({\n path: `/template/${id}`,\n method: 'DELETE',\n secure: true,\n format: 'json',\n ...params,\n }),\n };\n voiceLibrary = {\n /**\n * No description\n *\n * @tags Voice Library\n * @name VoiceLibraryControllerVoiceGetByProvider\n * @summary Get voices in Voice Library by Provider\n * @request GET:/voice-library/{provider}\n * @secure\n */\n voiceLibraryControllerVoiceGetByProvider: (provider, query, params = {}) => this.request({\n path: `/voice-library/${provider}`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Voice Library\n * @name VoiceLibraryControllerVoiceGetAccentsByProvider\n * @summary Get accents in Voice Library by Provider\n * @request GET:/voice-library/{provider}/accents\n * @secure\n */\n voiceLibraryControllerVoiceGetAccentsByProvider: (provider, params = {}) => this.request({\n path: `/voice-library/${provider}/accents`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Voice Library\n * @name VoiceLibraryControllerVoiceLibrarySyncByProvider\n * @summary Sync Private voices in Voice Library by Provider\n * @request POST:/voice-library/sync/{provider}\n * @secure\n */\n voiceLibraryControllerVoiceLibrarySyncByProvider: (provider, params = {}) => this.request({\n path: `/voice-library/sync/${provider}`,\n method: 'POST',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Voice Library\n * @name VoiceLibraryControllerVoiceLibrarySyncDefaultVoices\n * @summary Sync Default voices in Voice Library by Providers\n * @request POST:/voice-library/sync\n * @secure\n */\n voiceLibraryControllerVoiceLibrarySyncDefaultVoices: (data, params = {}) => this.request({\n path: `/voice-library/sync`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n };\n provider = {\n /**\n * No description\n *\n * @tags Providers\n * @name ProviderControllerGetWorkflows\n * @request GET:/{provider}/workflows\n * @secure\n */\n providerControllerGetWorkflows: (provider, query, params = {}) => this.request({\n path: `/${provider}/workflows`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Providers\n * @name ProviderControllerGetWorkflowTriggerHook\n * @request GET:/{provider}/workflows/{workflowId}/hooks\n * @secure\n */\n providerControllerGetWorkflowTriggerHook: (provider, workflowId, params = {}) => this.request({\n path: `/${provider}/workflows/${workflowId}/hooks`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Providers\n * @name ProviderControllerGetLocations\n * @request GET:/{provider}/locations\n * @secure\n */\n providerControllerGetLocations: (provider, params = {}) => this.request({\n path: `/${provider}/locations`,\n method: 'GET',\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Providers\n * @name VoiceProviderControllerSearchVoices\n * @summary Search Voice from Provider Voice Library.\n * @request GET:/{provider}/voices/search\n * @deprecated\n * @secure\n */\n voiceProviderControllerSearchVoices: (provider, query, params = {}) => this.request({\n path: `/${provider}/voices/search`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Providers\n * @name VoiceProviderControllerSearchVoice\n * @summary Search Voice from Provider Voice Library.\n * @request GET:/{provider}/voice/search\n * @secure\n */\n voiceProviderControllerSearchVoice: (provider, query, params = {}) => this.request({\n path: `/${provider}/voice/search`,\n method: 'GET',\n query: query,\n secure: true,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Providers\n * @name VoiceProviderControllerAddVoices\n * @summary Add Shared Voice to your Provider Account.\n * @request POST:/{provider}/voices/add\n * @deprecated\n * @secure\n */\n voiceProviderControllerAddVoices: (provider, data, params = {}) => this.request({\n path: `/${provider}/voices/add`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n /**\n * No description\n *\n * @tags Providers\n * @name VoiceProviderControllerAddVoice\n * @summary Add Shared Voice to your Provider Account.\n * @request POST:/{provider}/voice/add\n * @secure\n */\n voiceProviderControllerAddVoice: (provider, data, params = {}) => this.request({\n path: `/${provider}/voice/add`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.Json,\n format: 'json',\n ...params,\n }),\n };\n v11Labs = {\n /**\n * No description\n *\n * @tags Providers\n * @name VoiceProviderControllerCloneVoices\n * @summary Clone a voice to the provider account and add to Vapi Voice Library.\n * @request POST:/11labs/voice/clone\n * @secure\n */\n voiceProviderControllerCloneVoices: (data, params = {}) => this.request({\n path: `/11labs/voice/clone`,\n method: 'POST',\n body: data,\n secure: true,\n type: ContentType.FormData,\n ...params,\n }),\n };\n}\nexports.Api = Api;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.client = void 0;\nconst api_1 = require(\"./api\");\nconst api = new api_1.Api({\n baseUrl: \"https://api.vapi.ai\",\n baseApiParams: {\n secure: true,\n },\n securityWorker: async (securityData) => {\n if (securityData) {\n return {\n headers: {\n Authorization: `Bearer ${securityData}`,\n },\n };\n }\n },\n});\nexports.client = api;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst daily_js_1 = __importDefault(require(\"@daily-co/daily-js\"));\nconst events_1 = __importDefault(require(\"events\"));\nconst client_1 = require(\"./client\");\nasync function startAudioPlayer(player, track) {\n player.muted = false;\n player.autoplay = true;\n if (track != null) {\n player.srcObject = new MediaStream([track]);\n await player.play();\n }\n}\nasync function buildAudioPlayer(track, participantId) {\n const player = document.createElement('audio');\n player.dataset.participantId = participantId;\n document.body.appendChild(player);\n await startAudioPlayer(player, track);\n return player;\n}\nfunction destroyAudioPlayer(participantId) {\n const player = document.querySelector(`audio[data-participant-id=\"${participantId}\"]`);\n player?.remove();\n}\nfunction subscribeToTracks(e, call, isVideoRecordingEnabled, isVideoEnabled) {\n if (e.participant.local)\n return;\n call.updateParticipant(e.participant.session_id, {\n setSubscribedTracks: {\n audio: true,\n video: isVideoRecordingEnabled || isVideoEnabled,\n },\n });\n}\nclass VapiEventEmitter extends events_1.default {\n on(event, listener) {\n super.on(event, listener);\n return this;\n }\n once(event, listener) {\n super.once(event, listener);\n return this;\n }\n emit(event, ...args) {\n return super.emit(event, ...args);\n }\n removeListener(event, listener) {\n super.removeListener(event, listener);\n return this;\n }\n removeAllListeners(event) {\n super.removeAllListeners(event);\n return this;\n }\n}\nclass Vapi extends VapiEventEmitter {\n started = false;\n call = null;\n speakingTimeout = null;\n dailyCallConfig = {};\n dailyCallObject = {};\n hasEmittedCallEndedStatus = false;\n constructor(apiToken, apiBaseUrl, dailyCallConfig, dailyCallObject) {\n super();\n client_1.client.baseUrl = apiBaseUrl ?? 'https://api.vapi.ai';\n client_1.client.setSecurityData(apiToken);\n this.dailyCallConfig = dailyCallConfig ?? {};\n this.dailyCallObject = dailyCallObject ?? {};\n }\n cleanup() {\n this.started = false;\n this.hasEmittedCallEndedStatus = false;\n this.call?.destroy();\n this.call = null;\n this.speakingTimeout = null;\n }\n isMobileDevice() {\n if (typeof navigator === 'undefined') {\n return false;\n }\n const userAgent = navigator.userAgent;\n return /android|iphone|ipad|ipod|iemobile|blackberry|bada/i.test(userAgent.toLowerCase());\n }\n async sleep(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n async start(assistant, assistantOverrides, squad) {\n if (!assistant && !squad) {\n throw new Error('Assistant or Squad must be provided.');\n }\n if (this.started) {\n return null;\n }\n this.started = true;\n try {\n const webCall = (await client_1.client.call.callControllerCreateWebCall({\n assistant: typeof assistant === 'string' ? undefined : assistant,\n assistantId: typeof assistant === 'string' ? assistant : undefined,\n assistantOverrides,\n squad: typeof squad === 'string' ? undefined : squad,\n squadId: typeof squad === 'string' ? squad : undefined,\n })).data;\n if (this.call) {\n this.cleanup();\n }\n const isVideoRecordingEnabled = webCall?.artifactPlan?.videoRecordingEnabled ?? false;\n const isVideoEnabled = webCall.transport?.assistantVideoEnabled ?? false;\n this.call = daily_js_1.default.createCallObject({\n audioSource: this.dailyCallObject.audioSource ?? true,\n videoSource: this.dailyCallObject.videoSource ?? isVideoRecordingEnabled,\n dailyConfig: this.dailyCallConfig,\n });\n this.call.iframe()?.style.setProperty('display', 'none');\n this.call.on('left-meeting', () => {\n this.emit('call-end');\n if (!this.hasEmittedCallEndedStatus) {\n this.emit('message', {\n type: 'status-update',\n status: 'ended',\n 'endedReason': 'customer-ended-call',\n });\n this.hasEmittedCallEndedStatus = true;\n }\n if (isVideoRecordingEnabled) {\n this.call?.stopRecording();\n }\n this.cleanup();\n });\n this.call.on('error', (error) => {\n this.emit('error', error);\n if (isVideoRecordingEnabled) {\n this.call?.stopRecording();\n }\n });\n this.call.on('camera-error', (error) => {\n this.emit('error', error);\n });\n this.call.on('track-started', async (e) => {\n if (!e || !e.participant) {\n return;\n }\n if (e.participant?.local) {\n return;\n }\n if (e.participant?.user_name !== 'Vapi Speaker') {\n return;\n }\n if (e.track.kind === 'video') {\n this.emit('video', e.track);\n }\n if (e.track.kind === 'audio') {\n await buildAudioPlayer(e.track, e.participant.session_id);\n }\n this.call?.sendAppMessage('playable');\n });\n this.call.on('participant-joined', (e) => {\n if (!e || !this.call)\n return;\n subscribeToTracks(e, this.call, isVideoRecordingEnabled, isVideoEnabled);\n });\n this.call.on('participant-updated', (e) => {\n if (!e) {\n return;\n }\n this.emit('daily-participant-updated', e.participant);\n });\n this.call.on('participant-left', (e) => {\n if (!e) {\n return;\n }\n destroyAudioPlayer(e.participant.session_id);\n });\n // Allow mobile devices to finish processing the microphone permissions\n // request before joining the call and playing the assistant's audio\n if (this.isMobileDevice()) {\n await this.sleep(1000);\n }\n await this.call.join({\n // @ts-expect-error This exists\n url: webCall.webCallUrl,\n subscribeToTracksAutomatically: false,\n });\n if (isVideoRecordingEnabled) {\n const recordingRequestedTime = new Date().getTime();\n this.call.startRecording({\n width: 1280,\n height: 720,\n backgroundColor: '#FF1F2D3D',\n layout: {\n preset: 'default',\n },\n });\n this.call.on('recording-started', () => {\n this.send({\n type: 'control',\n control: 'say-first-message',\n videoRecordingStartDelaySeconds: (new Date().getTime() - recordingRequestedTime) / 1000,\n });\n });\n }\n this.call.startRemoteParticipantsAudioLevelObserver(100);\n this.call.on('remote-participants-audio-level', (e) => {\n if (e)\n this.handleRemoteParticipantsAudioLevel(e);\n });\n this.call.on('app-message', (e) => this.onAppMessage(e));\n this.call.on('nonfatal-error', (e) => {\n // https://docs.daily.co/reference/daily-js/events/meeting-events#type-audio-processor-error\n if (e?.type === 'audio-processor-error') {\n this.call\n ?.updateInputSettings({\n audio: {\n processor: {\n type: 'none',\n },\n },\n })\n .then(() => {\n this.call?.setLocalAudio(true);\n });\n }\n });\n this.call.updateInputSettings({\n audio: {\n processor: {\n type: 'noise-cancellation',\n },\n },\n });\n return webCall;\n }\n catch (e) {\n console.error(e);\n this.emit('error', e);\n this.cleanup();\n return null;\n }\n }\n onAppMessage(e) {\n if (!e) {\n return;\n }\n try {\n if (e.data === 'listening') {\n return this.emit('call-start');\n }\n else {\n try {\n const parsedMessage = JSON.parse(e.data);\n this.emit('message', parsedMessage);\n if (parsedMessage && 'type' in parsedMessage && 'status' in parsedMessage && parsedMessage.type === 'status-update' && parsedMessage.status === 'ended') {\n this.hasEmittedCallEndedStatus = true;\n }\n }\n catch (parseError) {\n console.log('Error parsing message data: ', parseError);\n }\n }\n }\n catch (e) {\n console.error(e);\n }\n }\n handleRemoteParticipantsAudioLevel(e) {\n const speechLevel = Object.values(e.participantsAudioLevel).reduce((a, b) => a + b, 0);\n this.emit('volume-level', Math.min(1, speechLevel / 0.15));\n const isSpeaking = speechLevel > 0.01;\n if (!isSpeaking) {\n return;\n }\n if (this.speakingTimeout) {\n clearTimeout(this.speakingTimeout);\n this.speakingTimeout = null;\n }\n else {\n this.emit('speech-start');\n }\n this.speakingTimeout = setTimeout(() => {\n this.emit('speech-end');\n this.speakingTimeout = null;\n }, 1000);\n }\n stop() {\n this.started = false;\n this.call?.destroy();\n this.call = null;\n }\n send(message) {\n this.call?.sendAppMessage(JSON.stringify(message));\n }\n setMuted(mute) {\n if (!this.call) {\n throw new Error('Call object is not available.');\n }\n this.call.setLocalAudio(!mute);\n }\n isMuted() {\n if (!this.call) {\n return false;\n }\n return this.call.localAudio() === false;\n }\n say(message, endCallAfterSpoken, interruptionsEnabled) {\n this.send({\n type: 'say',\n message,\n endCallAfterSpoken,\n interruptionsEnabled: interruptionsEnabled ?? false,\n });\n }\n setInputDevicesAsync(options) {\n this.call?.setInputDevicesAsync(options);\n }\n async increaseMicLevel(gain) {\n if (!this.call) {\n throw new Error('Call object is not available.');\n }\n try {\n const stream = await navigator.mediaDevices.getUserMedia({ audio: true });\n const audioContext = new AudioContext();\n const source = audioContext.createMediaStreamSource(stream);\n const gainNode = audioContext.createGain();\n gainNode.gain.value = gain;\n source.connect(gainNode);\n const destination = audioContext.createMediaStreamDestination();\n gainNode.connect(destination);\n const [boostedTrack] = destination.stream.getAudioTracks();\n await this.call.setInputDevicesAsync({ audioSource: boostedTrack });\n }\n catch (error) {\n console.error(\"Error adjusting microphone level:\", error);\n }\n }\n setOutputDeviceAsync(options) {\n this.call?.setOutputDeviceAsync(options);\n }\n getDailyCallObject() {\n return this.call;\n }\n startScreenSharing(displayMediaOptions, screenVideoSendSettings) {\n this.call?.startScreenShare({\n displayMediaOptions,\n screenVideoSendSettings,\n });\n }\n stopScreenSharing() {\n this.call?.stopScreenShare();\n }\n}\nexports.default = Vapi;\n","/*! decimal.js-light v2.5.1 https://github.com/MikeMcl/decimal.js-light/LICENCE */\r\n;(function (globalScope) {\r\n 'use strict';\r\n\r\n\r\n /*\r\n * decimal.js-light v2.5.1\r\n * An arbitrary-precision Decimal type for JavaScript.\r\n * https://github.com/MikeMcl/decimal.js-light\r\n * Copyright (c) 2020 Michael Mclaughlin \r\n * MIT Expat Licence\r\n */\r\n\r\n\r\n // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //\r\n\r\n\r\n // The limit on the value of `precision`, and on the value of the first argument to\r\n // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.\r\n var MAX_DIGITS = 1e9, // 0 to 1e9\r\n\r\n\r\n // The initial configuration properties of the Decimal constructor.\r\n Decimal = {\r\n\r\n // These values must be integers within the stated ranges (inclusive).\r\n // Most of these values can be changed during run-time using `Decimal.config`.\r\n\r\n // The maximum number of significant digits of the result of a calculation or base conversion.\r\n // E.g. `Decimal.config({ precision: 20 });`\r\n precision: 20, // 1 to MAX_DIGITS\r\n\r\n // The rounding mode used by default by `toInteger`, `toDecimalPlaces`, `toExponential`,\r\n // `toFixed`, `toPrecision` and `toSignificantDigits`.\r\n //\r\n // ROUND_UP 0 Away from zero.\r\n // ROUND_DOWN 1 Towards zero.\r\n // ROUND_CEIL 2 Towards +Infinity.\r\n // ROUND_FLOOR 3 Towards -Infinity.\r\n // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r\n // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r\n // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n //\r\n // E.g.\r\n // `Decimal.rounding = 4;`\r\n // `Decimal.rounding = Decimal.ROUND_HALF_UP;`\r\n rounding: 4, // 0 to 8\r\n\r\n // The exponent value at and beneath which `toString` returns exponential notation.\r\n // JavaScript numbers: -7\r\n toExpNeg: -7, // 0 to -MAX_E\r\n\r\n // The exponent value at and above which `toString` returns exponential notation.\r\n // JavaScript numbers: 21\r\n toExpPos: 21, // 0 to MAX_E\r\n\r\n // The natural logarithm of 10.\r\n // 115 digits\r\n LN10: '2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286'\r\n },\r\n\r\n\r\n // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //\r\n\r\n\r\n external = true,\r\n\r\n decimalError = '[DecimalError] ',\r\n invalidArgument = decimalError + 'Invalid argument: ',\r\n exponentOutOfRange = decimalError + 'Exponent out of range: ',\r\n\r\n mathfloor = Math.floor,\r\n mathpow = Math.pow,\r\n\r\n isDecimal = /^(\\d+(\\.\\d*)?|\\.\\d+)(e[+-]?\\d+)?$/i,\r\n\r\n ONE,\r\n BASE = 1e7,\r\n LOG_BASE = 7,\r\n MAX_SAFE_INTEGER = 9007199254740991,\r\n MAX_E = mathfloor(MAX_SAFE_INTEGER / LOG_BASE), // 1286742750677284\r\n\r\n // Decimal.prototype object\r\n P = {};\r\n\r\n\r\n // Decimal prototype methods\r\n\r\n\r\n /*\r\n * absoluteValue abs\r\n * comparedTo cmp\r\n * decimalPlaces dp\r\n * dividedBy div\r\n * dividedToIntegerBy idiv\r\n * equals eq\r\n * exponent\r\n * greaterThan gt\r\n * greaterThanOrEqualTo gte\r\n * isInteger isint\r\n * isNegative isneg\r\n * isPositive ispos\r\n * isZero\r\n * lessThan lt\r\n * lessThanOrEqualTo lte\r\n * logarithm log\r\n * minus sub\r\n * modulo mod\r\n * naturalExponential exp\r\n * naturalLogarithm ln\r\n * negated neg\r\n * plus add\r\n * precision sd\r\n * squareRoot sqrt\r\n * times mul\r\n * toDecimalPlaces todp\r\n * toExponential\r\n * toFixed\r\n * toInteger toint\r\n * toNumber\r\n * toPower pow\r\n * toPrecision\r\n * toSignificantDigits tosd\r\n * toString\r\n * valueOf val\r\n */\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the absolute value of this Decimal.\r\n *\r\n */\r\n P.absoluteValue = P.abs = function () {\r\n var x = new this.constructor(this);\r\n if (x.s) x.s = 1;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * Return\r\n * 1 if the value of this Decimal is greater than the value of `y`,\r\n * -1 if the value of this Decimal is less than the value of `y`,\r\n * 0 if they have the same value\r\n *\r\n */\r\n P.comparedTo = P.cmp = function (y) {\r\n var i, j, xdL, ydL,\r\n x = this;\r\n\r\n y = new x.constructor(y);\r\n\r\n // Signs differ?\r\n if (x.s !== y.s) return x.s || -y.s;\r\n\r\n // Compare exponents.\r\n if (x.e !== y.e) return x.e > y.e ^ x.s < 0 ? 1 : -1;\r\n\r\n xdL = x.d.length;\r\n ydL = y.d.length;\r\n\r\n // Compare digit by digit.\r\n for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {\r\n if (x.d[i] !== y.d[i]) return x.d[i] > y.d[i] ^ x.s < 0 ? 1 : -1;\r\n }\r\n\r\n // Compare lengths.\r\n return xdL === ydL ? 0 : xdL > ydL ^ x.s < 0 ? 1 : -1;\r\n };\r\n\r\n\r\n /*\r\n * Return the number of decimal places of the value of this Decimal.\r\n *\r\n */\r\n P.decimalPlaces = P.dp = function () {\r\n var x = this,\r\n w = x.d.length - 1,\r\n dp = (w - x.e) * LOG_BASE;\r\n\r\n // Subtract the number of trailing zeros of the last word.\r\n w = x.d[w];\r\n if (w) for (; w % 10 == 0; w /= 10) dp--;\r\n\r\n return dp < 0 ? 0 : dp;\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal divided by `y`, truncated to\r\n * `precision` significant digits.\r\n *\r\n */\r\n P.dividedBy = P.div = function (y) {\r\n return divide(this, new this.constructor(y));\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the integer part of dividing the value of this Decimal\r\n * by the value of `y`, truncated to `precision` significant digits.\r\n *\r\n */\r\n P.dividedToIntegerBy = P.idiv = function (y) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n return round(divide(x, new Ctor(y), 0, 1), Ctor.precision);\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.\r\n *\r\n */\r\n P.equals = P.eq = function (y) {\r\n return !this.cmp(y);\r\n };\r\n\r\n\r\n /*\r\n * Return the (base 10) exponent value of this Decimal (this.e is the base 10000000 exponent).\r\n *\r\n */\r\n P.exponent = function () {\r\n return getBase10Exponent(this);\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is greater than the value of `y`, otherwise return\r\n * false.\r\n *\r\n */\r\n P.greaterThan = P.gt = function (y) {\r\n return this.cmp(y) > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is greater than or equal to the value of `y`,\r\n * otherwise return false.\r\n *\r\n */\r\n P.greaterThanOrEqualTo = P.gte = function (y) {\r\n return this.cmp(y) >= 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is an integer, otherwise return false.\r\n *\r\n */\r\n P.isInteger = P.isint = function () {\r\n return this.e > this.d.length - 2;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is negative, otherwise return false.\r\n *\r\n */\r\n P.isNegative = P.isneg = function () {\r\n return this.s < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is positive, otherwise return false.\r\n *\r\n */\r\n P.isPositive = P.ispos = function () {\r\n return this.s > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is 0, otherwise return false.\r\n *\r\n */\r\n P.isZero = function () {\r\n return this.s === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is less than `y`, otherwise return false.\r\n *\r\n */\r\n P.lessThan = P.lt = function (y) {\r\n return this.cmp(y) < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.\r\n *\r\n */\r\n P.lessThanOrEqualTo = P.lte = function (y) {\r\n return this.cmp(y) < 1;\r\n };\r\n\r\n\r\n /*\r\n * Return the logarithm of the value of this Decimal to the specified base, truncated to\r\n * `precision` significant digits.\r\n *\r\n * If no base is specified, return log[10](x).\r\n *\r\n * log[base](x) = ln(x) / ln(base)\r\n *\r\n * The maximum error of the result is 1 ulp (unit in the last place).\r\n *\r\n * [base] {number|string|Decimal} The base of the logarithm.\r\n *\r\n */\r\n P.logarithm = P.log = function (base) {\r\n var r,\r\n x = this,\r\n Ctor = x.constructor,\r\n pr = Ctor.precision,\r\n wpr = pr + 5;\r\n\r\n // Default base is 10.\r\n if (base === void 0) {\r\n base = new Ctor(10);\r\n } else {\r\n base = new Ctor(base);\r\n\r\n // log[-b](x) = NaN\r\n // log[0](x) = NaN\r\n // log[1](x) = NaN\r\n if (base.s < 1 || base.eq(ONE)) throw Error(decimalError + 'NaN');\r\n }\r\n\r\n // log[b](-x) = NaN\r\n // log[b](0) = -Infinity\r\n if (x.s < 1) throw Error(decimalError + (x.s ? 'NaN' : '-Infinity'));\r\n\r\n // log[b](1) = 0\r\n if (x.eq(ONE)) return new Ctor(0);\r\n\r\n external = false;\r\n r = divide(ln(x, wpr), ln(base, wpr), wpr);\r\n external = true;\r\n\r\n return round(r, pr);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal minus `y`, truncated to\r\n * `precision` significant digits.\r\n *\r\n */\r\n P.minus = P.sub = function (y) {\r\n var x = this;\r\n y = new x.constructor(y);\r\n return x.s == y.s ? subtract(x, y) : add(x, (y.s = -y.s, y));\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal modulo `y`, truncated to\r\n * `precision` significant digits.\r\n *\r\n */\r\n P.modulo = P.mod = function (y) {\r\n var q,\r\n x = this,\r\n Ctor = x.constructor,\r\n pr = Ctor.precision;\r\n\r\n y = new Ctor(y);\r\n\r\n // x % 0 = NaN\r\n if (!y.s) throw Error(decimalError + 'NaN');\r\n\r\n // Return x if x is 0.\r\n if (!x.s) return round(new Ctor(x), pr);\r\n\r\n // Prevent rounding of intermediate calculations.\r\n external = false;\r\n q = divide(x, y, 0, 1).times(y);\r\n external = true;\r\n\r\n return x.minus(q);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the natural exponential of the value of this Decimal,\r\n * i.e. the base e raised to the power the value of this Decimal, truncated to `precision`\r\n * significant digits.\r\n *\r\n */\r\n P.naturalExponential = P.exp = function () {\r\n return exp(this);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,\r\n * truncated to `precision` significant digits.\r\n *\r\n */\r\n P.naturalLogarithm = P.ln = function () {\r\n return ln(this);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by\r\n * -1.\r\n *\r\n */\r\n P.negated = P.neg = function () {\r\n var x = new this.constructor(this);\r\n x.s = -x.s || 0;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal plus `y`, truncated to\r\n * `precision` significant digits.\r\n *\r\n */\r\n P.plus = P.add = function (y) {\r\n var x = this;\r\n y = new x.constructor(y);\r\n return x.s == y.s ? add(x, y) : subtract(x, (y.s = -y.s, y));\r\n };\r\n\r\n\r\n /*\r\n * Return the number of significant digits of the value of this Decimal.\r\n *\r\n * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.\r\n *\r\n */\r\n P.precision = P.sd = function (z) {\r\n var e, sd, w,\r\n x = this;\r\n\r\n if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);\r\n\r\n e = getBase10Exponent(x) + 1;\r\n w = x.d.length - 1;\r\n sd = w * LOG_BASE + 1;\r\n w = x.d[w];\r\n\r\n // If non-zero...\r\n if (w) {\r\n\r\n // Subtract the number of trailing zeros of the last word.\r\n for (; w % 10 == 0; w /= 10) sd--;\r\n\r\n // Add the number of digits of the first word.\r\n for (w = x.d[0]; w >= 10; w /= 10) sd++;\r\n }\r\n\r\n return z && e > sd ? e : sd;\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the square root of this Decimal, truncated to `precision`\r\n * significant digits.\r\n *\r\n */\r\n P.squareRoot = P.sqrt = function () {\r\n var e, n, pr, r, s, t, wpr,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n // Negative or zero?\r\n if (x.s < 1) {\r\n if (!x.s) return new Ctor(0);\r\n\r\n // sqrt(-x) = NaN\r\n throw Error(decimalError + 'NaN');\r\n }\r\n\r\n e = getBase10Exponent(x);\r\n external = false;\r\n\r\n // Initial estimate.\r\n s = Math.sqrt(+x);\r\n\r\n // Math.sqrt underflow/overflow?\r\n // Pass x to Math.sqrt as integer, then adjust the exponent of the result.\r\n if (s == 0 || s == 1 / 0) {\r\n n = digitsToString(x.d);\r\n if ((n.length + e) % 2 == 0) n += '0';\r\n s = Math.sqrt(n);\r\n e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new Ctor(n);\r\n } else {\r\n r = new Ctor(s.toString());\r\n }\r\n\r\n pr = Ctor.precision;\r\n s = wpr = pr + 3;\r\n\r\n // Newton-Raphson iteration.\r\n for (;;) {\r\n t = r;\r\n r = t.plus(divide(x, t, wpr + 2)).times(0.5);\r\n\r\n if (digitsToString(t.d).slice(0, wpr) === (n = digitsToString(r.d)).slice(0, wpr)) {\r\n n = n.slice(wpr - 3, wpr + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or\r\n // 4999, i.e. approaching a rounding boundary, continue the iteration.\r\n if (s == wpr && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the exact result as the\r\n // nines may infinitely repeat.\r\n round(t, pr + 1, 0);\r\n\r\n if (t.times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n } else if (n != '9999') {\r\n break;\r\n }\r\n\r\n wpr += 4;\r\n }\r\n }\r\n\r\n external = true;\r\n\r\n return round(r, pr);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal times `y`, truncated to\r\n * `precision` significant digits.\r\n *\r\n */\r\n P.times = P.mul = function (y) {\r\n var carry, e, i, k, r, rL, t, xdL, ydL,\r\n x = this,\r\n Ctor = x.constructor,\r\n xd = x.d,\r\n yd = (y = new Ctor(y)).d;\r\n\r\n // Return 0 if either is 0.\r\n if (!x.s || !y.s) return new Ctor(0);\r\n\r\n y.s *= x.s;\r\n e = x.e + y.e;\r\n xdL = xd.length;\r\n ydL = yd.length;\r\n\r\n // Ensure xd points to the longer array.\r\n if (xdL < ydL) {\r\n r = xd;\r\n xd = yd;\r\n yd = r;\r\n rL = xdL;\r\n xdL = ydL;\r\n ydL = rL;\r\n }\r\n\r\n // Initialise the result array with zeros.\r\n r = [];\r\n rL = xdL + ydL;\r\n for (i = rL; i--;) r.push(0);\r\n\r\n // Multiply!\r\n for (i = ydL; --i >= 0;) {\r\n carry = 0;\r\n for (k = xdL + i; k > i;) {\r\n t = r[k] + yd[i] * xd[k - i - 1] + carry;\r\n r[k--] = t % BASE | 0;\r\n carry = t / BASE | 0;\r\n }\r\n\r\n r[k] = (r[k] + carry) % BASE | 0;\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (; !r[--rL];) r.pop();\r\n\r\n if (carry) ++e;\r\n else r.shift();\r\n\r\n y.d = r;\r\n y.e = e;\r\n\r\n return external ? round(y, Ctor.precision) : y;\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`\r\n * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.\r\n *\r\n * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\n P.toDecimalPlaces = P.todp = function (dp, rm) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n\r\n x = new Ctor(x);\r\n if (dp === void 0) return x;\r\n\r\n checkInt32(dp, 0, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n return round(x, dp + getBase10Exponent(x) + 1, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this Decimal in exponential notation rounded to\r\n * `dp` fixed decimal places using rounding mode `rounding`.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\n P.toExponential = function (dp, rm) {\r\n var str,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (dp === void 0) {\r\n str = toString(x, true);\r\n } else {\r\n checkInt32(dp, 0, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n x = round(new Ctor(x), dp + 1, rm);\r\n str = toString(x, true, dp + 1);\r\n }\r\n\r\n return str;\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this Decimal in normal (fixed-point) notation to\r\n * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is\r\n * omitted.\r\n *\r\n * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.\r\n * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.\r\n * (-0).toFixed(3) is '0.000'.\r\n * (-0.5).toFixed(0) is '-0'.\r\n *\r\n */\r\n P.toFixed = function (dp, rm) {\r\n var str, y,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (dp === void 0) return toString(x);\r\n\r\n checkInt32(dp, 0, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n y = round(new Ctor(x), dp + getBase10Exponent(x) + 1, rm);\r\n str = toString(y.abs(), false, dp + getBase10Exponent(y) + 1);\r\n\r\n // To determine whether to add the minus sign look at the value before it was rounded,\r\n // i.e. look at `x` rather than `y`.\r\n return x.isneg() && !x.isZero() ? '-' + str : str;\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using\r\n * rounding mode `rounding`.\r\n *\r\n */\r\n P.toInteger = P.toint = function () {\r\n var x = this,\r\n Ctor = x.constructor;\r\n return round(new Ctor(x), getBase10Exponent(x) + 1, Ctor.rounding);\r\n };\r\n\r\n\r\n /*\r\n * Return the value of this Decimal converted to a number primitive.\r\n *\r\n */\r\n P.toNumber = function () {\r\n return +this;\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal raised to the power `y`,\r\n * truncated to `precision` significant digits.\r\n *\r\n * For non-integer or very large exponents pow(x, y) is calculated using\r\n *\r\n * x^y = exp(y*ln(x))\r\n *\r\n * The maximum error is 1 ulp (unit in last place).\r\n *\r\n * y {number|string|Decimal} The power to which to raise this Decimal.\r\n *\r\n */\r\n P.toPower = P.pow = function (y) {\r\n var e, k, pr, r, sign, yIsInt,\r\n x = this,\r\n Ctor = x.constructor,\r\n guard = 12,\r\n yn = +(y = new Ctor(y));\r\n\r\n // pow(x, 0) = 1\r\n if (!y.s) return new Ctor(ONE);\r\n\r\n x = new Ctor(x);\r\n\r\n // pow(0, y > 0) = 0\r\n // pow(0, y < 0) = Infinity\r\n if (!x.s) {\r\n if (y.s < 1) throw Error(decimalError + 'Infinity');\r\n return x;\r\n }\r\n\r\n // pow(1, y) = 1\r\n if (x.eq(ONE)) return x;\r\n\r\n pr = Ctor.precision;\r\n\r\n // pow(x, 1) = x\r\n if (y.eq(ONE)) return round(x, pr);\r\n\r\n e = y.e;\r\n k = y.d.length - 1;\r\n yIsInt = e >= k;\r\n sign = x.s;\r\n\r\n if (!yIsInt) {\r\n\r\n // pow(x < 0, y non-integer) = NaN\r\n if (sign < 0) throw Error(decimalError + 'NaN');\r\n\r\n // If y is a small integer use the 'exponentiation by squaring' algorithm.\r\n } else if ((k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {\r\n r = new Ctor(ONE);\r\n\r\n // Max k of 9007199254740991 takes 53 loop iterations.\r\n // Maximum digits array length; leaves [28, 34] guard digits.\r\n e = Math.ceil(pr / LOG_BASE + 4);\r\n\r\n external = false;\r\n\r\n for (;;) {\r\n if (k % 2) {\r\n r = r.times(x);\r\n truncate(r.d, e);\r\n }\r\n\r\n k = mathfloor(k / 2);\r\n if (k === 0) break;\r\n\r\n x = x.times(x);\r\n truncate(x.d, e);\r\n }\r\n\r\n external = true;\r\n\r\n return y.s < 0 ? new Ctor(ONE).div(r) : round(r, pr);\r\n }\r\n\r\n // Result is negative if x is negative and the last digit of integer y is odd.\r\n sign = sign < 0 && y.d[Math.max(e, k)] & 1 ? -1 : 1;\r\n\r\n x.s = 1;\r\n external = false;\r\n r = y.times(ln(x, pr + guard));\r\n external = true;\r\n r = exp(r);\r\n r.s = sign;\r\n\r\n return r;\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this Decimal rounded to `sd` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * Return exponential notation if `sd` is less than the number of digits necessary to represent\r\n * the integer part of the value in normal notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\n P.toPrecision = function (sd, rm) {\r\n var e, str,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (sd === void 0) {\r\n e = getBase10Exponent(x);\r\n str = toString(x, e <= Ctor.toExpNeg || e >= Ctor.toExpPos);\r\n } else {\r\n checkInt32(sd, 1, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n x = round(new Ctor(x), sd, rm);\r\n e = getBase10Exponent(x);\r\n str = toString(x, sd <= e || e <= Ctor.toExpNeg, sd);\r\n }\r\n\r\n return str;\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`\r\n * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if\r\n * omitted.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\n P.toSignificantDigits = P.tosd = function (sd, rm) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n\r\n if (sd === void 0) {\r\n sd = Ctor.precision;\r\n rm = Ctor.rounding;\r\n } else {\r\n checkInt32(sd, 1, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n }\r\n\r\n return round(new Ctor(x), sd, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this Decimal.\r\n *\r\n * Return exponential notation if this Decimal has a positive exponent equal to or greater than\r\n * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.\r\n *\r\n */\r\n P.toString = P.valueOf = P.val = P.toJSON = function () {\r\n var x = this,\r\n e = getBase10Exponent(x),\r\n Ctor = x.constructor;\r\n\r\n return toString(x, e <= Ctor.toExpNeg || e >= Ctor.toExpPos);\r\n };\r\n\r\n\r\n // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.\r\n\r\n\r\n /*\r\n * add P.minus, P.plus\r\n * checkInt32 P.todp, P.toExponential, P.toFixed, P.toPrecision, P.tosd\r\n * digitsToString P.log, P.sqrt, P.pow, toString, exp, ln\r\n * divide P.div, P.idiv, P.log, P.mod, P.sqrt, exp, ln\r\n * exp P.exp, P.pow\r\n * getBase10Exponent P.exponent, P.sd, P.toint, P.sqrt, P.todp, P.toFixed, P.toPrecision,\r\n * P.toString, divide, round, toString, exp, ln\r\n * getLn10 P.log, ln\r\n * getZeroString digitsToString, toString\r\n * ln P.log, P.ln, P.pow, exp\r\n * parseDecimal Decimal\r\n * round P.abs, P.idiv, P.log, P.minus, P.mod, P.neg, P.plus, P.toint, P.sqrt,\r\n * P.times, P.todp, P.toExponential, P.toFixed, P.pow, P.toPrecision, P.tosd,\r\n * divide, getLn10, exp, ln\r\n * subtract P.minus, P.plus\r\n * toString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf\r\n * truncate P.pow\r\n *\r\n * Throws: P.log, P.mod, P.sd, P.sqrt, P.pow, checkInt32, divide, round,\r\n * getLn10, exp, ln, parseDecimal, Decimal, config\r\n */\r\n\r\n\r\n function add(x, y) {\r\n var carry, d, e, i, k, len, xd, yd,\r\n Ctor = x.constructor,\r\n pr = Ctor.precision;\r\n\r\n // If either is zero...\r\n if (!x.s || !y.s) {\r\n\r\n // Return x if y is zero.\r\n // Return y if y is non-zero.\r\n if (!y.s) y = new Ctor(x);\r\n return external ? round(y, pr) : y;\r\n }\r\n\r\n xd = x.d;\r\n yd = y.d;\r\n\r\n // x and y are finite, non-zero numbers with the same sign.\r\n\r\n k = x.e;\r\n e = y.e;\r\n xd = xd.slice();\r\n i = k - e;\r\n\r\n // If base 1e7 exponents differ...\r\n if (i) {\r\n if (i < 0) {\r\n d = xd;\r\n i = -i;\r\n len = yd.length;\r\n } else {\r\n d = yd;\r\n e = k;\r\n len = xd.length;\r\n }\r\n\r\n // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.\r\n k = Math.ceil(pr / LOG_BASE);\r\n len = k > len ? k + 1 : len + 1;\r\n\r\n if (i > len) {\r\n i = len;\r\n d.length = 1;\r\n }\r\n\r\n // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.\r\n d.reverse();\r\n for (; i--;) d.push(0);\r\n d.reverse();\r\n }\r\n\r\n len = xd.length;\r\n i = yd.length;\r\n\r\n // If yd is longer than xd, swap xd and yd so xd points to the longer array.\r\n if (len - i < 0) {\r\n i = len;\r\n d = yd;\r\n yd = xd;\r\n xd = d;\r\n }\r\n\r\n // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.\r\n for (carry = 0; i;) {\r\n carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;\r\n xd[i] %= BASE;\r\n }\r\n\r\n if (carry) {\r\n xd.unshift(carry);\r\n ++e;\r\n }\r\n\r\n // Remove trailing zeros.\r\n // No need to check for zero, as +x + +y != 0 && -x + -y != 0\r\n for (len = xd.length; xd[--len] == 0;) xd.pop();\r\n\r\n y.d = xd;\r\n y.e = e;\r\n\r\n return external ? round(y, pr) : y;\r\n }\r\n\r\n\r\n function checkInt32(i, min, max) {\r\n if (i !== ~~i || i < min || i > max) {\r\n throw Error(invalidArgument + i);\r\n }\r\n }\r\n\r\n\r\n function digitsToString(d) {\r\n var i, k, ws,\r\n indexOfLastWord = d.length - 1,\r\n str = '',\r\n w = d[0];\r\n\r\n if (indexOfLastWord > 0) {\r\n str += w;\r\n for (i = 1; i < indexOfLastWord; i++) {\r\n ws = d[i] + '';\r\n k = LOG_BASE - ws.length;\r\n if (k) str += getZeroString(k);\r\n str += ws;\r\n }\r\n\r\n w = d[i];\r\n ws = w + '';\r\n k = LOG_BASE - ws.length;\r\n if (k) str += getZeroString(k);\r\n } else if (w === 0) {\r\n return '0';\r\n }\r\n\r\n // Remove trailing zeros of last w.\r\n for (; w % 10 === 0;) w /= 10;\r\n\r\n return str + w;\r\n }\r\n\r\n\r\n var divide = (function () {\r\n\r\n // Assumes non-zero x and k, and hence non-zero result.\r\n function multiplyInteger(x, k) {\r\n var temp,\r\n carry = 0,\r\n i = x.length;\r\n\r\n for (x = x.slice(); i--;) {\r\n temp = x[i] * k + carry;\r\n x[i] = temp % BASE | 0;\r\n carry = temp / BASE | 0;\r\n }\r\n\r\n if (carry) x.unshift(carry);\r\n\r\n return x;\r\n }\r\n\r\n function compare(a, b, aL, bL) {\r\n var i, r;\r\n\r\n if (aL != bL) {\r\n r = aL > bL ? 1 : -1;\r\n } else {\r\n for (i = r = 0; i < aL; i++) {\r\n if (a[i] != b[i]) {\r\n r = a[i] > b[i] ? 1 : -1;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return r;\r\n }\r\n\r\n function subtract(a, b, aL) {\r\n var i = 0;\r\n\r\n // Subtract b from a.\r\n for (; aL--;) {\r\n a[aL] -= i;\r\n i = a[aL] < b[aL] ? 1 : 0;\r\n a[aL] = i * BASE + a[aL] - b[aL];\r\n }\r\n\r\n // Remove leading zeros.\r\n for (; !a[0] && a.length > 1;) a.shift();\r\n }\r\n\r\n return function (x, y, pr, dp) {\r\n var cmp, e, i, k, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, yL, yz,\r\n Ctor = x.constructor,\r\n sign = x.s == y.s ? 1 : -1,\r\n xd = x.d,\r\n yd = y.d;\r\n\r\n // Either 0?\r\n if (!x.s) return new Ctor(x);\r\n if (!y.s) throw Error(decimalError + 'Division by zero');\r\n\r\n e = x.e - y.e;\r\n yL = yd.length;\r\n xL = xd.length;\r\n q = new Ctor(sign);\r\n qd = q.d = [];\r\n\r\n // Result exponent may be one less than e.\r\n for (i = 0; yd[i] == (xd[i] || 0); ) ++i;\r\n if (yd[i] > (xd[i] || 0)) --e;\r\n\r\n if (pr == null) {\r\n sd = pr = Ctor.precision;\r\n } else if (dp) {\r\n sd = pr + (getBase10Exponent(x) - getBase10Exponent(y)) + 1;\r\n } else {\r\n sd = pr;\r\n }\r\n\r\n if (sd < 0) return new Ctor(0);\r\n\r\n // Convert precision in number of base 10 digits to base 1e7 digits.\r\n sd = sd / LOG_BASE + 2 | 0;\r\n i = 0;\r\n\r\n // divisor < 1e7\r\n if (yL == 1) {\r\n k = 0;\r\n yd = yd[0];\r\n sd++;\r\n\r\n // k is the carry.\r\n for (; (i < xL || k) && sd--; i++) {\r\n t = k * BASE + (xd[i] || 0);\r\n qd[i] = t / yd | 0;\r\n k = t % yd | 0;\r\n }\r\n\r\n // divisor >= 1e7\r\n } else {\r\n\r\n // Normalise xd and yd so highest order digit of yd is >= BASE/2\r\n k = BASE / (yd[0] + 1) | 0;\r\n\r\n if (k > 1) {\r\n yd = multiplyInteger(yd, k);\r\n xd = multiplyInteger(xd, k);\r\n yL = yd.length;\r\n xL = xd.length;\r\n }\r\n\r\n xi = yL;\r\n rem = xd.slice(0, yL);\r\n remL = rem.length;\r\n\r\n // Add zeros to make remainder as long as divisor.\r\n for (; remL < yL;) rem[remL++] = 0;\r\n\r\n yz = yd.slice();\r\n yz.unshift(0);\r\n yd0 = yd[0];\r\n\r\n if (yd[1] >= BASE / 2) ++yd0;\r\n\r\n do {\r\n k = 0;\r\n\r\n // Compare divisor and remainder.\r\n cmp = compare(yd, rem, yL, remL);\r\n\r\n // If divisor < remainder.\r\n if (cmp < 0) {\r\n\r\n // Calculate trial digit, k.\r\n rem0 = rem[0];\r\n if (yL != remL) rem0 = rem0 * BASE + (rem[1] || 0);\r\n\r\n // k will be how many times the divisor goes into the current remainder.\r\n k = rem0 / yd0 | 0;\r\n\r\n // Algorithm:\r\n // 1. product = divisor * trial digit (k)\r\n // 2. if product > remainder: product -= divisor, k--\r\n // 3. remainder -= product\r\n // 4. if product was < remainder at 2:\r\n // 5. compare new remainder and divisor\r\n // 6. If remainder > divisor: remainder -= divisor, k++\r\n\r\n if (k > 1) {\r\n if (k >= BASE) k = BASE - 1;\r\n\r\n // product = divisor * trial digit.\r\n prod = multiplyInteger(yd, k);\r\n prodL = prod.length;\r\n remL = rem.length;\r\n\r\n // Compare product and remainder.\r\n cmp = compare(prod, rem, prodL, remL);\r\n\r\n // product > remainder.\r\n if (cmp == 1) {\r\n k--;\r\n\r\n // Subtract divisor from product.\r\n subtract(prod, yL < prodL ? yz : yd, prodL);\r\n }\r\n } else {\r\n\r\n // cmp is -1.\r\n // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1\r\n // to avoid it. If k is 1 there is a need to compare yd and rem again below.\r\n if (k == 0) cmp = k = 1;\r\n prod = yd.slice();\r\n }\r\n\r\n prodL = prod.length;\r\n if (prodL < remL) prod.unshift(0);\r\n\r\n // Subtract product from remainder.\r\n subtract(rem, prod, remL);\r\n\r\n // If product was < previous remainder.\r\n if (cmp == -1) {\r\n remL = rem.length;\r\n\r\n // Compare divisor and new remainder.\r\n cmp = compare(yd, rem, yL, remL);\r\n\r\n // If divisor < new remainder, subtract divisor from remainder.\r\n if (cmp < 1) {\r\n k++;\r\n\r\n // Subtract divisor from remainder.\r\n subtract(rem, yL < remL ? yz : yd, remL);\r\n }\r\n }\r\n\r\n remL = rem.length;\r\n } else if (cmp === 0) {\r\n k++;\r\n rem = [0];\r\n } // if cmp === 1, k will be 0\r\n\r\n // Add the next digit, k, to the result array.\r\n qd[i++] = k;\r\n\r\n // Update the remainder.\r\n if (cmp && rem[0]) {\r\n rem[remL++] = xd[xi] || 0;\r\n } else {\r\n rem = [xd[xi]];\r\n remL = 1;\r\n }\r\n\r\n } while ((xi++ < xL || rem[0] !== void 0) && sd--);\r\n }\r\n\r\n // Leading zero?\r\n if (!qd[0]) qd.shift();\r\n\r\n q.e = e;\r\n\r\n return round(q, dp ? pr + getBase10Exponent(q) + 1 : pr);\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the natural exponential of `x` truncated to `sd`\r\n * significant digits.\r\n *\r\n * Taylor/Maclaurin series.\r\n *\r\n * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...\r\n *\r\n * Argument reduction:\r\n * Repeat x = x / 32, k += 5, until |x| < 0.1\r\n * exp(x) = exp(x / 2^k)^(2^k)\r\n *\r\n * Previously, the argument was initially reduced by\r\n * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)\r\n * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was\r\n * found to be slower than just dividing repeatedly by 32 as above.\r\n *\r\n * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)\r\n *\r\n * exp(x) is non-terminating for any finite, non-zero x.\r\n *\r\n */\r\n function exp(x, sd) {\r\n var denominator, guard, pow, sum, t, wpr,\r\n i = 0,\r\n k = 0,\r\n Ctor = x.constructor,\r\n pr = Ctor.precision;\r\n\r\n if (getBase10Exponent(x) > 16) throw Error(exponentOutOfRange + getBase10Exponent(x));\r\n\r\n // exp(0) = 1\r\n if (!x.s) return new Ctor(ONE);\r\n\r\n if (sd == null) {\r\n external = false;\r\n wpr = pr;\r\n } else {\r\n wpr = sd;\r\n }\r\n\r\n t = new Ctor(0.03125);\r\n\r\n while (x.abs().gte(0.1)) {\r\n x = x.times(t); // x = x / 2^5\r\n k += 5;\r\n }\r\n\r\n // Estimate the precision increase necessary to ensure the first 4 rounding digits are correct.\r\n guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;\r\n wpr += guard;\r\n denominator = pow = sum = new Ctor(ONE);\r\n Ctor.precision = wpr;\r\n\r\n for (;;) {\r\n pow = round(pow.times(x), wpr);\r\n denominator = denominator.times(++i);\r\n t = sum.plus(divide(pow, denominator, wpr));\r\n\r\n if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {\r\n while (k--) sum = round(sum.times(sum), wpr);\r\n Ctor.precision = pr;\r\n return sd == null ? (external = true, round(sum, pr)) : sum;\r\n }\r\n\r\n sum = t;\r\n }\r\n }\r\n\r\n\r\n // Calculate the base 10 exponent from the base 1e7 exponent.\r\n function getBase10Exponent(x) {\r\n var e = x.e * LOG_BASE,\r\n w = x.d[0];\r\n\r\n // Add the number of digits of the first word of the digits array.\r\n for (; w >= 10; w /= 10) e++;\r\n return e;\r\n }\r\n\r\n\r\n function getLn10(Ctor, sd, pr) {\r\n\r\n if (sd > Ctor.LN10.sd()) {\r\n\r\n\r\n // Reset global state in case the exception is caught.\r\n external = true;\r\n if (pr) Ctor.precision = pr;\r\n throw Error(decimalError + 'LN10 precision limit exceeded');\r\n }\r\n\r\n return round(new Ctor(Ctor.LN10), sd);\r\n }\r\n\r\n\r\n function getZeroString(k) {\r\n var zs = '';\r\n for (; k--;) zs += '0';\r\n return zs;\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the natural logarithm of `x` truncated to `sd` significant\r\n * digits.\r\n *\r\n * ln(n) is non-terminating (n != 1)\r\n *\r\n */\r\n function ln(y, sd) {\r\n var c, c0, denominator, e, numerator, sum, t, wpr, x2,\r\n n = 1,\r\n guard = 10,\r\n x = y,\r\n xd = x.d,\r\n Ctor = x.constructor,\r\n pr = Ctor.precision;\r\n\r\n // ln(-x) = NaN\r\n // ln(0) = -Infinity\r\n if (x.s < 1) throw Error(decimalError + (x.s ? 'NaN' : '-Infinity'));\r\n\r\n // ln(1) = 0\r\n if (x.eq(ONE)) return new Ctor(0);\r\n\r\n if (sd == null) {\r\n external = false;\r\n wpr = pr;\r\n } else {\r\n wpr = sd;\r\n }\r\n\r\n if (x.eq(10)) {\r\n if (sd == null) external = true;\r\n return getLn10(Ctor, wpr);\r\n }\r\n\r\n wpr += guard;\r\n Ctor.precision = wpr;\r\n c = digitsToString(xd);\r\n c0 = c.charAt(0);\r\n e = getBase10Exponent(x);\r\n\r\n if (Math.abs(e) < 1.5e15) {\r\n\r\n // Argument reduction.\r\n // The series converges faster the closer the argument is to 1, so using\r\n // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b\r\n // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,\r\n // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can\r\n // later be divided by this number, then separate out the power of 10 using\r\n // ln(a*10^b) = ln(a) + b*ln(10).\r\n\r\n // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).\r\n //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {\r\n // max n is 6 (gives 0.7 - 1.3)\r\n while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {\r\n x = x.times(y);\r\n c = digitsToString(x.d);\r\n c0 = c.charAt(0);\r\n n++;\r\n }\r\n\r\n e = getBase10Exponent(x);\r\n\r\n if (c0 > 1) {\r\n x = new Ctor('0.' + c);\r\n e++;\r\n } else {\r\n x = new Ctor(c0 + '.' + c.slice(1));\r\n }\r\n } else {\r\n\r\n // The argument reduction method above may result in overflow if the argument y is a massive\r\n // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this\r\n // function using ln(x*10^e) = ln(x) + e*ln(10).\r\n t = getLn10(Ctor, wpr + 2, pr).times(e + '');\r\n x = ln(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);\r\n\r\n Ctor.precision = pr;\r\n return sd == null ? (external = true, round(x, pr)) : x;\r\n }\r\n\r\n // x is reduced to a value near 1.\r\n\r\n // Taylor series.\r\n // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)\r\n // where x = (y - 1)/(y + 1) (|x| < 1)\r\n sum = numerator = x = divide(x.minus(ONE), x.plus(ONE), wpr);\r\n x2 = round(x.times(x), wpr);\r\n denominator = 3;\r\n\r\n for (;;) {\r\n numerator = round(numerator.times(x2), wpr);\r\n t = sum.plus(divide(numerator, new Ctor(denominator), wpr));\r\n\r\n if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {\r\n sum = sum.times(2);\r\n\r\n // Reverse the argument reduction.\r\n if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));\r\n sum = divide(sum, new Ctor(n), wpr);\r\n\r\n Ctor.precision = pr;\r\n return sd == null ? (external = true, round(sum, pr)) : sum;\r\n }\r\n\r\n sum = t;\r\n denominator += 2;\r\n }\r\n }\r\n\r\n\r\n /*\r\n * Parse the value of a new Decimal `x` from string `str`.\r\n */\r\n function parseDecimal(x, str) {\r\n var e, i, len;\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n\r\n // Exponential form?\r\n if ((i = str.search(/e/i)) > 0) {\r\n\r\n // Determine exponent.\r\n if (e < 0) e = i;\r\n e += +str.slice(i + 1);\r\n str = str.substring(0, i);\r\n } else if (e < 0) {\r\n\r\n // Integer.\r\n e = str.length;\r\n }\r\n\r\n // Determine leading zeros.\r\n for (i = 0; str.charCodeAt(i) === 48;) ++i;\r\n\r\n // Determine trailing zeros.\r\n for (len = str.length; str.charCodeAt(len - 1) === 48;) --len;\r\n str = str.slice(i, len);\r\n\r\n if (str) {\r\n len -= i;\r\n e = e - i - 1;\r\n x.e = mathfloor(e / LOG_BASE);\r\n x.d = [];\r\n\r\n // Transform base\r\n\r\n // e is the base 10 exponent.\r\n // i is where to slice str to get the first word of the digits array.\r\n i = (e + 1) % LOG_BASE;\r\n if (e < 0) i += LOG_BASE;\r\n\r\n if (i < len) {\r\n if (i) x.d.push(+str.slice(0, i));\r\n for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));\r\n str = str.slice(i);\r\n i = LOG_BASE - str.length;\r\n } else {\r\n i -= len;\r\n }\r\n\r\n for (; i--;) str += '0';\r\n x.d.push(+str);\r\n\r\n if (external && (x.e > MAX_E || x.e < -MAX_E)) throw Error(exponentOutOfRange + e);\r\n } else {\r\n\r\n // Zero.\r\n x.s = 0;\r\n x.e = 0;\r\n x.d = [0];\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n /*\r\n * Round `x` to `sd` significant digits, using rounding mode `rm` if present (truncate otherwise).\r\n */\r\n function round(x, sd, rm) {\r\n var i, j, k, n, rd, doRound, w, xdi,\r\n xd = x.d;\r\n\r\n // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.\r\n // w: the word of xd which contains the rounding digit, a base 1e7 number.\r\n // xdi: the index of w within xd.\r\n // n: the number of digits of w.\r\n // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if\r\n // they had leading zeros)\r\n // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).\r\n\r\n // Get the length of the first word of the digits array xd.\r\n for (n = 1, k = xd[0]; k >= 10; k /= 10) n++;\r\n i = sd - n;\r\n\r\n // Is the rounding digit in the first word of xd?\r\n if (i < 0) {\r\n i += LOG_BASE;\r\n j = sd;\r\n w = xd[xdi = 0];\r\n } else {\r\n xdi = Math.ceil((i + 1) / LOG_BASE);\r\n k = xd.length;\r\n if (xdi >= k) return x;\r\n w = k = xd[xdi];\r\n\r\n // Get the number of digits of w.\r\n for (n = 1; k >= 10; k /= 10) n++;\r\n\r\n // Get the index of rd within w.\r\n i %= LOG_BASE;\r\n\r\n // Get the index of rd within w, adjusted for leading zeros.\r\n // The number of leading zeros of w is given by LOG_BASE - n.\r\n j = i - LOG_BASE + n;\r\n }\r\n\r\n if (rm !== void 0) {\r\n k = mathpow(10, n - j - 1);\r\n\r\n // Get the rounding digit at index j of w.\r\n rd = w / k % 10 | 0;\r\n\r\n // Are there any non-zero digits after the rounding digit?\r\n doRound = sd < 0 || xd[xdi + 1] !== void 0 || w % k;\r\n\r\n // The expression `w % mathpow(10, n - j - 1)` returns all the digits of w to the right of the\r\n // digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression will give\r\n // 714.\r\n\r\n doRound = rm < 4\r\n ? (rd || doRound) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : rd > 5 || rd == 5 && (rm == 4 || doRound || rm == 6 &&\r\n\r\n // Check whether the digit to the left of the rounding digit is odd.\r\n ((i > 0 ? j > 0 ? w / mathpow(10, n - j) : 0 : xd[xdi - 1]) % 10) & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n }\r\n\r\n if (sd < 1 || !xd[0]) {\r\n if (doRound) {\r\n k = getBase10Exponent(x);\r\n xd.length = 1;\r\n\r\n // Convert sd to decimal places.\r\n sd = sd - k - 1;\r\n\r\n // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r\n xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);\r\n x.e = mathfloor(-sd / LOG_BASE) || 0;\r\n } else {\r\n xd.length = 1;\r\n\r\n // Zero.\r\n xd[0] = x.e = x.s = 0;\r\n }\r\n\r\n return x;\r\n }\r\n\r\n // Remove excess digits.\r\n if (i == 0) {\r\n xd.length = xdi;\r\n k = 1;\r\n xdi--;\r\n } else {\r\n xd.length = xdi + 1;\r\n k = mathpow(10, LOG_BASE - i);\r\n\r\n // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r\n // j > 0 means i > number of leading zeros of w.\r\n xd[xdi] = j > 0 ? (w / mathpow(10, n - j) % mathpow(10, j) | 0) * k : 0;\r\n }\r\n\r\n if (doRound) {\r\n for (;;) {\r\n\r\n // Is the digit to be rounded up in the first word of xd?\r\n if (xdi == 0) {\r\n if ((xd[0] += k) == BASE) {\r\n xd[0] = 1;\r\n ++x.e;\r\n }\r\n\r\n break;\r\n } else {\r\n xd[xdi] += k;\r\n if (xd[xdi] != BASE) break;\r\n xd[xdi--] = 0;\r\n k = 1;\r\n }\r\n }\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (i = xd.length; xd[--i] === 0;) xd.pop();\r\n\r\n if (external && (x.e > MAX_E || x.e < -MAX_E)) {\r\n throw Error(exponentOutOfRange + getBase10Exponent(x));\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n function subtract(x, y) {\r\n var d, e, i, j, k, len, xd, xe, xLTy, yd,\r\n Ctor = x.constructor,\r\n pr = Ctor.precision;\r\n\r\n // Return y negated if x is zero.\r\n // Return x if y is zero and x is non-zero.\r\n if (!x.s || !y.s) {\r\n if (y.s) y.s = -y.s;\r\n else y = new Ctor(x);\r\n return external ? round(y, pr) : y;\r\n }\r\n\r\n xd = x.d;\r\n yd = y.d;\r\n\r\n // x and y are non-zero numbers with the same sign.\r\n\r\n e = y.e;\r\n xe = x.e;\r\n xd = xd.slice();\r\n k = xe - e;\r\n\r\n // If exponents differ...\r\n if (k) {\r\n xLTy = k < 0;\r\n\r\n if (xLTy) {\r\n d = xd;\r\n k = -k;\r\n len = yd.length;\r\n } else {\r\n d = yd;\r\n e = xe;\r\n len = xd.length;\r\n }\r\n\r\n // Numbers with massively different exponents would result in a very high number of zeros\r\n // needing to be prepended, but this can be avoided while still ensuring correct rounding by\r\n // limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.\r\n i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;\r\n\r\n if (k > i) {\r\n k = i;\r\n d.length = 1;\r\n }\r\n\r\n // Prepend zeros to equalise exponents.\r\n d.reverse();\r\n for (i = k; i--;) d.push(0);\r\n d.reverse();\r\n\r\n // Base 1e7 exponents equal.\r\n } else {\r\n\r\n // Check digits to determine which is the bigger number.\r\n\r\n i = xd.length;\r\n len = yd.length;\r\n xLTy = i < len;\r\n if (xLTy) len = i;\r\n\r\n for (i = 0; i < len; i++) {\r\n if (xd[i] != yd[i]) {\r\n xLTy = xd[i] < yd[i];\r\n break;\r\n }\r\n }\r\n\r\n k = 0;\r\n }\r\n\r\n if (xLTy) {\r\n d = xd;\r\n xd = yd;\r\n yd = d;\r\n y.s = -y.s;\r\n }\r\n\r\n len = xd.length;\r\n\r\n // Append zeros to xd if shorter.\r\n // Don't add zeros to yd if shorter as subtraction only needs to start at yd length.\r\n for (i = yd.length - len; i > 0; --i) xd[len++] = 0;\r\n\r\n // Subtract yd from xd.\r\n for (i = yd.length; i > k;) {\r\n if (xd[--i] < yd[i]) {\r\n for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;\r\n --xd[j];\r\n xd[i] += BASE;\r\n }\r\n\r\n xd[i] -= yd[i];\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (; xd[--len] === 0;) xd.pop();\r\n\r\n // Remove leading zeros and adjust exponent accordingly.\r\n for (; xd[0] === 0; xd.shift()) --e;\r\n\r\n // Zero?\r\n if (!xd[0]) return new Ctor(0);\r\n\r\n y.d = xd;\r\n y.e = e;\r\n\r\n //return external && xd.length >= pr / LOG_BASE ? round(y, pr) : y;\r\n return external ? round(y, pr) : y;\r\n }\r\n\r\n\r\n function toString(x, isExp, sd) {\r\n var k,\r\n e = getBase10Exponent(x),\r\n str = digitsToString(x.d),\r\n len = str.length;\r\n\r\n if (isExp) {\r\n if (sd && (k = sd - len) > 0) {\r\n str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);\r\n } else if (len > 1) {\r\n str = str.charAt(0) + '.' + str.slice(1);\r\n }\r\n\r\n str = str + (e < 0 ? 'e' : 'e+') + e;\r\n } else if (e < 0) {\r\n str = '0.' + getZeroString(-e - 1) + str;\r\n if (sd && (k = sd - len) > 0) str += getZeroString(k);\r\n } else if (e >= len) {\r\n str += getZeroString(e + 1 - len);\r\n if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);\r\n } else {\r\n if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);\r\n if (sd && (k = sd - len) > 0) {\r\n if (e + 1 === len) str += '.';\r\n str += getZeroString(k);\r\n }\r\n }\r\n\r\n return x.s < 0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // Does not strip trailing zeros.\r\n function truncate(arr, len) {\r\n if (arr.length > len) {\r\n arr.length = len;\r\n return true;\r\n }\r\n }\r\n\r\n\r\n // Decimal methods\r\n\r\n\r\n /*\r\n * clone\r\n * config/set\r\n */\r\n\r\n\r\n /*\r\n * Create and return a Decimal constructor with the same configuration properties as this Decimal\r\n * constructor.\r\n *\r\n */\r\n function clone(obj) {\r\n var i, p, ps;\r\n\r\n /*\r\n * The Decimal constructor and exported function.\r\n * Return a new Decimal instance.\r\n *\r\n * value {number|string|Decimal} A numeric value.\r\n *\r\n */\r\n function Decimal(value) {\r\n var x = this;\r\n\r\n // Decimal called without new.\r\n if (!(x instanceof Decimal)) return new Decimal(value);\r\n\r\n // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor\r\n // which points to Object.\r\n x.constructor = Decimal;\r\n\r\n // Duplicate.\r\n if (value instanceof Decimal) {\r\n x.s = value.s;\r\n x.e = value.e;\r\n x.d = (value = value.d) ? value.slice() : value;\r\n return;\r\n }\r\n\r\n if (typeof value === 'number') {\r\n\r\n // Reject Infinity/NaN.\r\n if (value * 0 !== 0) {\r\n throw Error(invalidArgument + value);\r\n }\r\n\r\n if (value > 0) {\r\n x.s = 1;\r\n } else if (value < 0) {\r\n value = -value;\r\n x.s = -1;\r\n } else {\r\n x.s = 0;\r\n x.e = 0;\r\n x.d = [0];\r\n return;\r\n }\r\n\r\n // Fast path for small integers.\r\n if (value === ~~value && value < 1e7) {\r\n x.e = 0;\r\n x.d = [value];\r\n return;\r\n }\r\n\r\n return parseDecimal(x, value.toString());\r\n } else if (typeof value !== 'string') {\r\n throw Error(invalidArgument + value);\r\n }\r\n\r\n // Minus sign?\r\n if (value.charCodeAt(0) === 45) {\r\n value = value.slice(1);\r\n x.s = -1;\r\n } else {\r\n x.s = 1;\r\n }\r\n\r\n if (isDecimal.test(value)) parseDecimal(x, value);\r\n else throw Error(invalidArgument + value);\r\n }\r\n\r\n Decimal.prototype = P;\r\n\r\n Decimal.ROUND_UP = 0;\r\n Decimal.ROUND_DOWN = 1;\r\n Decimal.ROUND_CEIL = 2;\r\n Decimal.ROUND_FLOOR = 3;\r\n Decimal.ROUND_HALF_UP = 4;\r\n Decimal.ROUND_HALF_DOWN = 5;\r\n Decimal.ROUND_HALF_EVEN = 6;\r\n Decimal.ROUND_HALF_CEIL = 7;\r\n Decimal.ROUND_HALF_FLOOR = 8;\r\n\r\n Decimal.clone = clone;\r\n Decimal.config = Decimal.set = config;\r\n\r\n if (obj === void 0) obj = {};\r\n if (obj) {\r\n ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'LN10'];\r\n for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];\r\n }\r\n\r\n Decimal.config(obj);\r\n\r\n return Decimal;\r\n }\r\n\r\n\r\n /*\r\n * Configure global settings for a Decimal constructor.\r\n *\r\n * `obj` is an object with one or more of the following properties,\r\n *\r\n * precision {number}\r\n * rounding {number}\r\n * toExpNeg {number}\r\n * toExpPos {number}\r\n *\r\n * E.g. Decimal.config({ precision: 20, rounding: 4 })\r\n *\r\n */\r\n function config(obj) {\r\n if (!obj || typeof obj !== 'object') {\r\n throw Error(decimalError + 'Object expected');\r\n }\r\n var i, p, v,\r\n ps = [\r\n 'precision', 1, MAX_DIGITS,\r\n 'rounding', 0, 8,\r\n 'toExpNeg', -1 / 0, 0,\r\n 'toExpPos', 0, 1 / 0\r\n ];\r\n\r\n for (i = 0; i < ps.length; i += 3) {\r\n if ((v = obj[p = ps[i]]) !== void 0) {\r\n if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;\r\n else throw Error(invalidArgument + p + ': ' + v);\r\n }\r\n }\r\n\r\n if ((v = obj[p = 'LN10']) !== void 0) {\r\n if (v == Math.LN10) this[p] = new this(v);\r\n else throw Error(invalidArgument + p + ': ' + v);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n\r\n // Create and configure initial Decimal constructor.\r\n Decimal = clone(Decimal);\r\n\r\n Decimal['default'] = Decimal.Decimal = Decimal;\r\n\r\n // Internal constant.\r\n ONE = new Decimal(1);\r\n\r\n\r\n // Export.\r\n\r\n\r\n // AMD.\r\n if (typeof define == 'function' && define.amd) {\r\n define(function () {\r\n return Decimal;\r\n });\r\n\r\n // Node and other environments that support module.exports.\r\n } else if (typeof module != 'undefined' && module.exports) {\r\n module.exports = Decimal;\r\n\r\n // Browser.\r\n } else {\r\n if (!globalScope) {\r\n globalScope = typeof self != 'undefined' && self && self.self == self\r\n ? self : Function('return this')();\r\n }\r\n\r\n globalScope.Decimal = Decimal;\r\n }\r\n})(this);\r\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n","'use strict';\n\nvar reactIs = require('react-is');\n\n/**\n * Copyright 2015, Yahoo! Inc.\n * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.\n */\nvar REACT_STATICS = {\n childContextTypes: true,\n contextType: true,\n contextTypes: true,\n defaultProps: true,\n displayName: true,\n getDefaultProps: true,\n getDerivedStateFromError: true,\n getDerivedStateFromProps: true,\n mixins: true,\n propTypes: true,\n type: true\n};\nvar KNOWN_STATICS = {\n name: true,\n length: true,\n prototype: true,\n caller: true,\n callee: true,\n arguments: true,\n arity: true\n};\nvar FORWARD_REF_STATICS = {\n '$$typeof': true,\n render: true,\n defaultProps: true,\n displayName: true,\n propTypes: true\n};\nvar MEMO_STATICS = {\n '$$typeof': true,\n compare: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n type: true\n};\nvar TYPE_STATICS = {};\nTYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;\nTYPE_STATICS[reactIs.Memo] = MEMO_STATICS;\n\nfunction getStatics(component) {\n // React v16.11 and below\n if (reactIs.isMemo(component)) {\n return MEMO_STATICS;\n } // React v16.12 and above\n\n\n return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;\n}\n\nvar defineProperty = Object.defineProperty;\nvar getOwnPropertyNames = Object.getOwnPropertyNames;\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar getPrototypeOf = Object.getPrototypeOf;\nvar objectPrototype = Object.prototype;\nfunction hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {\n if (typeof sourceComponent !== 'string') {\n // don't hoist over string (html) components\n if (objectPrototype) {\n var inheritedComponent = getPrototypeOf(sourceComponent);\n\n if (inheritedComponent && inheritedComponent !== objectPrototype) {\n hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);\n }\n }\n\n var keys = getOwnPropertyNames(sourceComponent);\n\n if (getOwnPropertySymbols) {\n keys = keys.concat(getOwnPropertySymbols(sourceComponent));\n }\n\n var targetStatics = getStatics(targetComponent);\n var sourceStatics = getStatics(sourceComponent);\n\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n\n if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {\n var descriptor = getOwnPropertyDescriptor(sourceComponent, key);\n\n try {\n // Avoid failures from read-only properties\n defineProperty(targetComponent, key, descriptor);\n } catch (e) {}\n }\n }\n }\n\n return targetComponent;\n}\n\nmodule.exports = hoistNonReactStatics;\n","/** @license React v16.13.1\n * react-is.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'use strict';var b=\"function\"===typeof Symbol&&Symbol.for,c=b?Symbol.for(\"react.element\"):60103,d=b?Symbol.for(\"react.portal\"):60106,e=b?Symbol.for(\"react.fragment\"):60107,f=b?Symbol.for(\"react.strict_mode\"):60108,g=b?Symbol.for(\"react.profiler\"):60114,h=b?Symbol.for(\"react.provider\"):60109,k=b?Symbol.for(\"react.context\"):60110,l=b?Symbol.for(\"react.async_mode\"):60111,m=b?Symbol.for(\"react.concurrent_mode\"):60111,n=b?Symbol.for(\"react.forward_ref\"):60112,p=b?Symbol.for(\"react.suspense\"):60113,q=b?\nSymbol.for(\"react.suspense_list\"):60120,r=b?Symbol.for(\"react.memo\"):60115,t=b?Symbol.for(\"react.lazy\"):60116,v=b?Symbol.for(\"react.block\"):60121,w=b?Symbol.for(\"react.fundamental\"):60117,x=b?Symbol.for(\"react.responder\"):60118,y=b?Symbol.for(\"react.scope\"):60119;\nfunction z(a){if(\"object\"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;\nexports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};\nexports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};\nexports.isValidElementType=function(a){return\"string\"===typeof a||\"function\"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||\"object\"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-is.production.min.js');\n} else {\n module.exports = require('./cjs/react-is.development.js');\n}\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nmodule.exports = DataView;\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 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 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 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 getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nmodule.exports = Promise;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nmodule.exports = Set;\n","var MapCache = require('./_MapCache'),\n setCacheAdd = require('./_setCacheAdd'),\n setCacheHas = require('./_setCacheHas');\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\nmodule.exports = SetCache;\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 root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nmodule.exports = Uint8Array;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nmodule.exports = WeakMap;\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","/**\n * A specialized version of `_.every` 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 {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n */\nfunction arrayEvery(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 false;\n }\n }\n return true;\n}\n\nmodule.exports = arrayEvery;\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\nmodule.exports = arrayFilter;\n","var baseIndexOf = require('./_baseIndexOf');\n\n/**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludes(array, value) {\n var length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n}\n\nmodule.exports = arrayIncludes;\n","/**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludesWith(array, value, comparator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (comparator(value, array[index])) {\n return true;\n }\n }\n return false;\n}\n\nmodule.exports = arrayIncludesWith;\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 * 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\nmodule.exports = arrayMap;\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\nmodule.exports = arrayPush;\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\nmodule.exports = arraySome;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nmodule.exports = asciiToArray;\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 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 baseForOwn = require('./_baseForOwn'),\n createBaseEach = require('./_createBaseEach');\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\nmodule.exports = baseEach;\n","var baseEach = require('./_baseEach');\n\n/**\n * The base implementation of `_.every` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`\n */\nfunction baseEvery(collection, predicate) {\n var result = true;\n baseEach(collection, function(value, index, collection) {\n result = !!predicate(value, index, collection);\n return result;\n });\n return result;\n}\n\nmodule.exports = baseEvery;\n","var isSymbol = require('./isSymbol');\n\n/**\n * The base implementation of methods like `_.max` and `_.min` which accepts a\n * `comparator` to determine the extremum value.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The iteratee invoked per iteration.\n * @param {Function} comparator The comparator used to compare values.\n * @returns {*} Returns the extremum value.\n */\nfunction baseExtremum(array, iteratee, comparator) {\n var index = -1,\n length = array.length;\n\n while (++index < length) {\n var value = array[index],\n current = iteratee(value);\n\n if (current != null && (computed === undefined\n ? (current === current && !isSymbol(current))\n : comparator(current, computed)\n )) {\n var computed = current,\n result = value;\n }\n }\n return result;\n}\n\nmodule.exports = baseExtremum;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nmodule.exports = baseFindIndex;\n","var arrayPush = require('./_arrayPush'),\n isFlattenable = require('./_isFlattenable');\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\nmodule.exports = baseFlatten;\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 baseFor = require('./_baseFor'),\n keys = require('./keys');\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\nmodule.exports = baseForOwn;\n","var castPath = require('./_castPath'),\n toKey = require('./_toKey');\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\nmodule.exports = baseGet;\n","var arrayPush = require('./_arrayPush'),\n isArray = require('./isArray');\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\nmodule.exports = baseGetAllKeys;\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 * The base implementation of `_.gt` which doesn't coerce arguments.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than `other`,\n * else `false`.\n */\nfunction baseGt(value, other) {\n return value > other;\n}\n\nmodule.exports = baseGt;\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\nmodule.exports = baseHasIn;\n","var baseFindIndex = require('./_baseFindIndex'),\n baseIsNaN = require('./_baseIsNaN'),\n strictIndexOf = require('./_strictIndexOf');\n\n/**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseIndexOf(array, value, fromIndex) {\n return value === value\n ? strictIndexOf(array, value, fromIndex)\n : baseFindIndex(array, baseIsNaN, fromIndex);\n}\n\nmodule.exports = baseIndexOf;\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 baseIsEqualDeep = require('./_baseIsEqualDeep'),\n isObjectLike = require('./isObjectLike');\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\nmodule.exports = baseIsEqual;\n","var Stack = require('./_Stack'),\n equalArrays = require('./_equalArrays'),\n equalByTag = require('./_equalByTag'),\n equalObjects = require('./_equalObjects'),\n getTag = require('./_getTag'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isTypedArray = require('./isTypedArray');\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\nmodule.exports = baseIsEqualDeep;\n","var Stack = require('./_Stack'),\n baseIsEqual = require('./_baseIsEqual');\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\nmodule.exports = baseIsMatch;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nmodule.exports = baseIsNaN;\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","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","var baseMatches = require('./_baseMatches'),\n baseMatchesProperty = require('./_baseMatchesProperty'),\n identity = require('./identity'),\n isArray = require('./isArray'),\n property = require('./property');\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\nmodule.exports = baseIteratee;\n","var isPrototype = require('./_isPrototype'),\n nativeKeys = require('./_nativeKeys');\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\nmodule.exports = baseKeys;\n","/**\n * The base implementation of `_.lt` which doesn't coerce arguments.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than `other`,\n * else `false`.\n */\nfunction baseLt(value, other) {\n return value < other;\n}\n\nmodule.exports = baseLt;\n","var baseEach = require('./_baseEach'),\n isArrayLike = require('./isArrayLike');\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\nmodule.exports = baseMap;\n","var baseIsMatch = require('./_baseIsMatch'),\n getMatchData = require('./_getMatchData'),\n matchesStrictComparable = require('./_matchesStrictComparable');\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\nmodule.exports = baseMatches;\n","var baseIsEqual = require('./_baseIsEqual'),\n get = require('./get'),\n hasIn = require('./hasIn'),\n isKey = require('./_isKey'),\n isStrictComparable = require('./_isStrictComparable'),\n matchesStrictComparable = require('./_matchesStrictComparable'),\n toKey = require('./_toKey');\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\nmodule.exports = baseMatchesProperty;\n","var arrayMap = require('./_arrayMap'),\n baseGet = require('./_baseGet'),\n baseIteratee = require('./_baseIteratee'),\n baseMap = require('./_baseMap'),\n baseSortBy = require('./_baseSortBy'),\n baseUnary = require('./_baseUnary'),\n compareMultiple = require('./_compareMultiple'),\n identity = require('./identity'),\n isArray = require('./isArray');\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\nmodule.exports = baseOrderBy;\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\nmodule.exports = baseProperty;\n","var baseGet = require('./_baseGet');\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\nmodule.exports = basePropertyDeep;\n","/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeCeil = Math.ceil,\n nativeMax = Math.max;\n\n/**\n * The base implementation of `_.range` and `_.rangeRight` which doesn't\n * coerce arguments.\n *\n * @private\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @param {number} step The value to increment or decrement by.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the range of numbers.\n */\nfunction baseRange(start, end, step, fromRight) {\n var index = -1,\n length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),\n result = Array(length);\n\n while (length--) {\n result[fromRight ? length : ++index] = start;\n start += step;\n }\n return result;\n}\n\nmodule.exports = baseRange;\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 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","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nmodule.exports = baseSlice;\n","var baseEach = require('./_baseEach');\n\n/**\n * The base implementation of `_.some` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection 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 baseSome(collection, predicate) {\n var result;\n\n baseEach(collection, function(value, index, collection) {\n result = predicate(value, index, collection);\n return !result;\n });\n return !!result;\n}\n\nmodule.exports = baseSome;\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\nmodule.exports = baseSortBy;\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","var Symbol = require('./_Symbol'),\n arrayMap = require('./_arrayMap'),\n isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\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\nmodule.exports = baseToString;\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","/**\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 SetCache = require('./_SetCache'),\n arrayIncludes = require('./_arrayIncludes'),\n arrayIncludesWith = require('./_arrayIncludesWith'),\n cacheHas = require('./_cacheHas'),\n createSet = require('./_createSet'),\n setToArray = require('./_setToArray');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * The base implementation of `_.uniqBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\nfunction baseUniq(array, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n length = array.length,\n isCommon = true,\n result = [],\n seen = result;\n\n if (comparator) {\n isCommon = false;\n includes = arrayIncludesWith;\n }\n else if (length >= LARGE_ARRAY_SIZE) {\n var set = iteratee ? null : createSet(array);\n if (set) {\n return setToArray(set);\n }\n isCommon = false;\n includes = cacheHas;\n seen = new SetCache;\n }\n else {\n seen = iteratee ? [] : result;\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var seenIndex = seen.length;\n while (seenIndex--) {\n if (seen[seenIndex] === computed) {\n continue outer;\n }\n }\n if (iteratee) {\n seen.push(computed);\n }\n result.push(value);\n }\n else if (!includes(seen, computed, comparator)) {\n if (seen !== result) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n}\n\nmodule.exports = baseUniq;\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\nmodule.exports = cacheHas;\n","var isArray = require('./isArray'),\n isKey = require('./_isKey'),\n stringToPath = require('./_stringToPath'),\n toString = require('./toString');\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\nmodule.exports = castPath;\n","var baseSlice = require('./_baseSlice');\n\n/**\n * Casts `array` to a slice if it's needed.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {number} start The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the cast slice.\n */\nfunction castSlice(array, start, end) {\n var length = array.length;\n end = end === undefined ? length : end;\n return (!start && end >= length) ? array : baseSlice(array, start, end);\n}\n\nmodule.exports = castSlice;\n","var isSymbol = require('./isSymbol');\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\nmodule.exports = compareAscending;\n","var compareAscending = require('./_compareAscending');\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\nmodule.exports = compareMultiple;\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 isArrayLike = require('./isArrayLike');\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\nmodule.exports = createBaseEach;\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 castSlice = require('./_castSlice'),\n hasUnicode = require('./_hasUnicode'),\n stringToArray = require('./_stringToArray'),\n toString = require('./toString');\n\n/**\n * Creates a function like `_.lowerFirst`.\n *\n * @private\n * @param {string} methodName The name of the `String` case method to use.\n * @returns {Function} Returns the new case function.\n */\nfunction createCaseFirst(methodName) {\n return function(string) {\n string = toString(string);\n\n var strSymbols = hasUnicode(string)\n ? stringToArray(string)\n : undefined;\n\n var chr = strSymbols\n ? strSymbols[0]\n : string.charAt(0);\n\n var trailing = strSymbols\n ? castSlice(strSymbols, 1).join('')\n : string.slice(1);\n\n return chr[methodName]() + trailing;\n };\n}\n\nmodule.exports = createCaseFirst;\n","var baseIteratee = require('./_baseIteratee'),\n isArrayLike = require('./isArrayLike'),\n keys = require('./keys');\n\n/**\n * Creates a `_.find` or `_.findLast` function.\n *\n * @private\n * @param {Function} findIndexFunc The function to find the collection index.\n * @returns {Function} Returns the new find function.\n */\nfunction createFind(findIndexFunc) {\n return function(collection, predicate, fromIndex) {\n var iterable = Object(collection);\n if (!isArrayLike(collection)) {\n var iteratee = baseIteratee(predicate, 3);\n collection = keys(collection);\n predicate = function(key) { return iteratee(iterable[key], key, iterable); };\n }\n var index = findIndexFunc(collection, predicate, fromIndex);\n return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;\n };\n}\n\nmodule.exports = createFind;\n","var baseRange = require('./_baseRange'),\n isIterateeCall = require('./_isIterateeCall'),\n toFinite = require('./toFinite');\n\n/**\n * Creates a `_.range` or `_.rangeRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new range function.\n */\nfunction createRange(fromRight) {\n return function(start, end, step) {\n if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {\n end = step = undefined;\n }\n // Ensure the sign of `-0` is preserved.\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);\n return baseRange(start, end, step, fromRight);\n };\n}\n\nmodule.exports = createRange;\n","var Set = require('./_Set'),\n noop = require('./noop'),\n setToArray = require('./_setToArray');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Creates a set object of `values`.\n *\n * @private\n * @param {Array} values The values to add to the set.\n * @returns {Object} Returns the new set.\n */\nvar createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n return new Set(values);\n};\n\nmodule.exports = createSet;\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 SetCache = require('./_SetCache'),\n arraySome = require('./_arraySome'),\n cacheHas = require('./_cacheHas');\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\nmodule.exports = equalArrays;\n","var Symbol = require('./_Symbol'),\n Uint8Array = require('./_Uint8Array'),\n eq = require('./eq'),\n equalArrays = require('./_equalArrays'),\n mapToArray = require('./_mapToArray'),\n setToArray = require('./_setToArray');\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\nmodule.exports = equalByTag;\n","var getAllKeys = require('./_getAllKeys');\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\nmodule.exports = equalObjects;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nmodule.exports = freeGlobal;\n","var baseGetAllKeys = require('./_baseGetAllKeys'),\n getSymbols = require('./_getSymbols'),\n keys = require('./keys');\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\nmodule.exports = getAllKeys;\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 isStrictComparable = require('./_isStrictComparable'),\n keys = require('./keys');\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\nmodule.exports = getMatchData;\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 overArg = require('./_overArg');\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nmodule.exports = getPrototype;\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","var arrayFilter = require('./_arrayFilter'),\n stubArray = require('./stubArray');\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\nmodule.exports = getSymbols;\n","var DataView = require('./_DataView'),\n Map = require('./_Map'),\n Promise = require('./_Promise'),\n Set = require('./_Set'),\n WeakMap = require('./_WeakMap'),\n baseGetTag = require('./_baseGetTag'),\n toSource = require('./_toSource');\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\nmodule.exports = getTag;\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 castPath = require('./_castPath'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isIndex = require('./_isIndex'),\n isLength = require('./isLength'),\n toKey = require('./_toKey');\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\nmodule.exports = hasPath;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nmodule.exports = hasUnicode;\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 Symbol = require('./_Symbol'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray');\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\nmodule.exports = isFlattenable;\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 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 isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\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\nmodule.exports = isKey;\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 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 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 isObject = require('./isObject');\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\nmodule.exports = isStrictComparable;\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","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 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","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","/**\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\nmodule.exports = mapToArray;\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\nmodule.exports = matchesStrictComparable;\n","var memoize = require('./memoize');\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\nmodule.exports = memoizeCapped;\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 overArg = require('./_overArg');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nmodule.exports = nativeKeys;\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","/** 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","/**\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 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","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","/** 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\nmodule.exports = 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\nmodule.exports = setCacheHas;\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\nmodule.exports = setToArray;\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","/** 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 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","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","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nmodule.exports = strictIndexOf;\n","var asciiToArray = require('./_asciiToArray'),\n hasUnicode = require('./_hasUnicode'),\n unicodeToArray = require('./_unicodeToArray');\n\n/**\n * Converts `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction stringToArray(string) {\n return hasUnicode(string)\n ? unicodeToArray(string)\n : asciiToArray(string);\n}\n\nmodule.exports = stringToArray;\n","var memoizeCapped = require('./_memoizeCapped');\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\nmodule.exports = stringToPath;\n","var isSymbol = require('./isSymbol');\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\nmodule.exports = toKey;\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","/** 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","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nmodule.exports = unicodeToArray;\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 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","/**\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 arrayEvery = require('./_arrayEvery'),\n baseEvery = require('./_baseEvery'),\n baseIteratee = require('./_baseIteratee'),\n isArray = require('./isArray'),\n isIterateeCall = require('./_isIterateeCall');\n\n/**\n * Checks if `predicate` returns truthy for **all** elements of `collection`.\n * Iteration is stopped once `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * **Note:** This method returns `true` for\n * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because\n * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of\n * elements of empty collections.\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} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n * @example\n *\n * _.every([true, 1, null, 'yes'], Boolean);\n * // => false\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.every(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.every(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.every(users, 'active');\n * // => false\n */\nfunction every(collection, predicate, guard) {\n var func = isArray(collection) ? arrayEvery : baseEvery;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, baseIteratee(predicate, 3));\n}\n\nmodule.exports = every;\n","var createFind = require('./_createFind'),\n findIndex = require('./findIndex');\n\n/**\n * Iterates over elements of `collection`, returning the first element\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false },\n * { 'user': 'pebbles', 'age': 1, 'active': true }\n * ];\n *\n * _.find(users, function(o) { return o.age < 40; });\n * // => object for 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.find(users, { 'age': 1, 'active': true });\n * // => object for 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.find(users, ['active', false]);\n * // => object for 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.find(users, 'active');\n * // => object for 'barney'\n */\nvar find = createFind(findIndex);\n\nmodule.exports = find;\n","var baseFindIndex = require('./_baseFindIndex'),\n baseIteratee = require('./_baseIteratee'),\n toInteger = require('./toInteger');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * This method is like `_.find` except that it returns the index of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.findIndex(users, function(o) { return o.user == 'barney'; });\n * // => 0\n *\n * // The `_.matches` iteratee shorthand.\n * _.findIndex(users, { 'user': 'fred', 'active': false });\n * // => 1\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findIndex(users, ['active', false]);\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.findIndex(users, 'active');\n * // => 2\n */\nfunction findIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseFindIndex(array, baseIteratee(predicate, 3), index);\n}\n\nmodule.exports = findIndex;\n","var baseFlatten = require('./_baseFlatten'),\n map = require('./map');\n\n/**\n * Creates a flattened array of values by running each element in `collection`\n * thru `iteratee` and flattening the mapped results. The iteratee is invoked\n * with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [n, n];\n * }\n *\n * _.flatMap([1, 2], duplicate);\n * // => [1, 1, 2, 2]\n */\nfunction flatMap(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), 1);\n}\n\nmodule.exports = flatMap;\n","var baseGet = require('./_baseGet');\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\nmodule.exports = get;\n","var baseHasIn = require('./_baseHasIn'),\n hasPath = require('./_hasPath');\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\nmodule.exports = hasIn;\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","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","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 baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]';\n\n/**\n * Checks if `value` is classified as a boolean primitive or 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 boolean, else `false`.\n * @example\n *\n * _.isBoolean(false);\n * // => true\n *\n * _.isBoolean(null);\n * // => false\n */\nfunction isBoolean(value) {\n return value === true || value === false ||\n (isObjectLike(value) && baseGetTag(value) == boolTag);\n}\n\nmodule.exports = isBoolean;\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 baseIsEqual = require('./_baseIsEqual');\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\nmodule.exports = isEqual;\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","/** 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 isNumber = require('./isNumber');\n\n/**\n * Checks if `value` is `NaN`.\n *\n * **Note:** This method is based on\n * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as\n * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for\n * `undefined` and other non-number values.\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 `NaN`, else `false`.\n * @example\n *\n * _.isNaN(NaN);\n * // => true\n *\n * _.isNaN(new Number(NaN));\n * // => true\n *\n * isNaN(undefined);\n * // => true\n *\n * _.isNaN(undefined);\n * // => false\n */\nfunction isNaN(value) {\n // An `NaN` primitive is the only value that is not equal to itself.\n // Perform the `toStringTag` check first to avoid errors with some\n // ActiveX objects in IE.\n return isNumber(value) && value != +value;\n}\n\nmodule.exports = isNaN;\n","/**\n * Checks if `value` is `null` or `undefined`.\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 nullish, else `false`.\n * @example\n *\n * _.isNil(null);\n * // => true\n *\n * _.isNil(void 0);\n * // => true\n *\n * _.isNil(NaN);\n * // => false\n */\nfunction isNil(value) {\n return value == null;\n}\n\nmodule.exports = isNil;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar numberTag = '[object Number]';\n\n/**\n * Checks if `value` is classified as a `Number` primitive or object.\n *\n * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are\n * classified as numbers, use the `_.isFinite` method.\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 number, else `false`.\n * @example\n *\n * _.isNumber(3);\n * // => true\n *\n * _.isNumber(Number.MIN_VALUE);\n * // => true\n *\n * _.isNumber(Infinity);\n * // => true\n *\n * _.isNumber('3');\n * // => false\n */\nfunction isNumber(value) {\n return typeof value == 'number' ||\n (isObjectLike(value) && baseGetTag(value) == numberTag);\n}\n\nmodule.exports = isNumber;\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","/**\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 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 isArray = require('./isArray'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar stringTag = '[object String]';\n\n/**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a string, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\nfunction isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);\n}\n\nmodule.exports = isString;\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 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","var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeys = require('./_baseKeys'),\n isArrayLike = require('./isArrayLike');\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\nmodule.exports = keys;\n","/**\n * Gets the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the last element of `array`.\n * @example\n *\n * _.last([1, 2, 3]);\n * // => 3\n */\nfunction last(array) {\n var length = array == null ? 0 : array.length;\n return length ? array[length - 1] : undefined;\n}\n\nmodule.exports = last;\n","var arrayMap = require('./_arrayMap'),\n baseIteratee = require('./_baseIteratee'),\n baseMap = require('./_baseMap'),\n isArray = require('./isArray');\n\n/**\n * Creates an array of values by running each element in `collection` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.\n *\n * The guarded methods are:\n * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,\n * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,\n * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,\n * `template`, `trim`, `trimEnd`, `trimStart`, and `words`\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} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * _.map([4, 8], square);\n * // => [16, 64]\n *\n * _.map({ 'a': 4, 'b': 8 }, square);\n * // => [16, 64] (iteration order is not guaranteed)\n *\n * var users = [\n * { 'user': 'barney' },\n * { 'user': 'fred' }\n * ];\n *\n * // The `_.property` iteratee shorthand.\n * _.map(users, 'user');\n * // => ['barney', 'fred']\n */\nfunction map(collection, iteratee) {\n var func = isArray(collection) ? arrayMap : baseMap;\n return func(collection, baseIteratee(iteratee, 3));\n}\n\nmodule.exports = map;\n","var baseAssignValue = require('./_baseAssignValue'),\n baseForOwn = require('./_baseForOwn'),\n baseIteratee = require('./_baseIteratee');\n\n/**\n * Creates an object with the same keys as `object` and values generated\n * by running each own enumerable string keyed property of `object` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapKeys\n * @example\n *\n * var users = {\n * 'fred': { 'user': 'fred', 'age': 40 },\n * 'pebbles': { 'user': 'pebbles', 'age': 1 }\n * };\n *\n * _.mapValues(users, function(o) { return o.age; });\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n *\n * // The `_.property` iteratee shorthand.\n * _.mapValues(users, 'age');\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n */\nfunction mapValues(object, iteratee) {\n var result = {};\n iteratee = baseIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, key, iteratee(value, key, object));\n });\n return result;\n}\n\nmodule.exports = mapValues;\n","var baseExtremum = require('./_baseExtremum'),\n baseGt = require('./_baseGt'),\n identity = require('./identity');\n\n/**\n * Computes the maximum value of `array`. If `array` is empty or falsey,\n * `undefined` is returned.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Math\n * @param {Array} array The array to iterate over.\n * @returns {*} Returns the maximum value.\n * @example\n *\n * _.max([4, 2, 8, 6]);\n * // => 8\n *\n * _.max([]);\n * // => undefined\n */\nfunction max(array) {\n return (array && array.length)\n ? baseExtremum(array, identity, baseGt)\n : undefined;\n}\n\nmodule.exports = max;\n","var MapCache = require('./_MapCache');\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\nmodule.exports = memoize;\n","var baseExtremum = require('./_baseExtremum'),\n baseLt = require('./_baseLt'),\n identity = require('./identity');\n\n/**\n * Computes the minimum value of `array`. If `array` is empty or falsey,\n * `undefined` is returned.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Math\n * @param {Array} array The array to iterate over.\n * @returns {*} Returns the minimum value.\n * @example\n *\n * _.min([4, 2, 8, 6]);\n * // => 2\n *\n * _.min([]);\n * // => undefined\n */\nfunction min(array) {\n return (array && array.length)\n ? baseExtremum(array, identity, baseLt)\n : undefined;\n}\n\nmodule.exports = min;\n","/**\n * This method returns `undefined`.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Util\n * @example\n *\n * _.times(2, _.noop);\n * // => [undefined, undefined]\n */\nfunction noop() {\n // No operation performed.\n}\n\nmodule.exports = noop;\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","var baseProperty = require('./_baseProperty'),\n basePropertyDeep = require('./_basePropertyDeep'),\n isKey = require('./_isKey'),\n toKey = require('./_toKey');\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\nmodule.exports = property;\n","var createRange = require('./_createRange');\n\n/**\n * Creates an array of numbers (positive and/or negative) progressing from\n * `start` up to, but not including, `end`. A step of `-1` is used if a negative\n * `start` is specified without an `end` or `step`. If `end` is not specified,\n * it's set to `start` with `start` then set to `0`.\n *\n * **Note:** JavaScript follows the IEEE-754 standard for resolving\n * floating-point values which can produce unexpected results.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {number} [start=0] The start of the range.\n * @param {number} end The end of the range.\n * @param {number} [step=1] The value to increment or decrement by.\n * @returns {Array} Returns the range of numbers.\n * @see _.inRange, _.rangeRight\n * @example\n *\n * _.range(4);\n * // => [0, 1, 2, 3]\n *\n * _.range(-4);\n * // => [0, -1, -2, -3]\n *\n * _.range(1, 5);\n * // => [1, 2, 3, 4]\n *\n * _.range(0, 20, 5);\n * // => [0, 5, 10, 15]\n *\n * _.range(0, -4, -1);\n * // => [0, -1, -2, -3]\n *\n * _.range(1, 4, 0);\n * // => [1, 1, 1]\n *\n * _.range(0);\n * // => []\n */\nvar range = createRange();\n\nmodule.exports = range;\n","var arraySome = require('./_arraySome'),\n baseIteratee = require('./_baseIteratee'),\n baseSome = require('./_baseSome'),\n isArray = require('./isArray'),\n isIterateeCall = require('./_isIterateeCall');\n\n/**\n * Checks if `predicate` returns truthy for **any** element of `collection`.\n * Iteration is stopped once `predicate` returns truthy. The predicate is\n * invoked with three arguments: (value, index|key, collection).\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} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n * @example\n *\n * _.some([null, 0, 'yes', false], Boolean);\n * // => true\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.some(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.some(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.some(users, 'active');\n * // => true\n */\nfunction some(collection, predicate, guard) {\n var func = isArray(collection) ? arraySome : baseSome;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, baseIteratee(predicate, 3));\n}\n\nmodule.exports = some;\n","var baseFlatten = require('./_baseFlatten'),\n baseOrderBy = require('./_baseOrderBy'),\n baseRest = require('./_baseRest'),\n isIterateeCall = require('./_isIterateeCall');\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\nmodule.exports = sortBy;\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\nmodule.exports = stubArray;\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 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","var toNumber = require('./toNumber');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0,\n MAX_INTEGER = 1.7976931348623157e+308;\n\n/**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\nfunction toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n}\n\nmodule.exports = toFinite;\n","var toFinite = require('./toFinite');\n\n/**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\nfunction toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n}\n\nmodule.exports = toInteger;\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 baseToString = require('./_baseToString');\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\nmodule.exports = toString;\n","var baseIteratee = require('./_baseIteratee'),\n baseUniq = require('./_baseUniq');\n\n/**\n * This method is like `_.uniq` except that it accepts `iteratee` which is\n * invoked for each element in `array` to generate the criterion by which\n * uniqueness is computed. The order of result values is determined by the\n * order they occur in the array. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniqBy([2.1, 1.2, 2.3], Math.floor);\n * // => [2.1, 1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\nfunction uniqBy(array, iteratee) {\n return (array && array.length) ? baseUniq(array, baseIteratee(iteratee, 2)) : [];\n}\n\nmodule.exports = uniqBy;\n","var createCaseFirst = require('./_createCaseFirst');\n\n/**\n * Converts the first character of `string` to upper case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.upperFirst('fred');\n * // => 'Fred'\n *\n * _.upperFirst('FRED');\n * // => 'FRED'\n */\nvar upperFirst = createCaseFirst('toUpperCase');\n\nmodule.exports = upperFirst;\n","\"use strict\";\n\nvar isodate = require(\"@segment/isodate\");\nvar milliseconds = require(\"./milliseconds\");\nvar seconds = require(\"./seconds\");\n\nvar objProto = Object.prototype;\nvar toStr = objProto.toString;\n\nfunction isDate(value) {\n return toStr.call(value) === \"[object Date]\";\n}\n\nfunction isNumber(value) {\n return toStr.call(value) === \"[object Number]\";\n}\n\n/**\n * Returns a new Javascript Date object, allowing a variety of extra input types\n * over the native Date constructor.\n *\n * @param {Date|string|number} val\n */\nmodule.exports = function newDate(val) {\n if (isDate(val)) return val;\n if (isNumber(val)) return new Date(toMs(val));\n\n // date strings\n if (isodate.is(val)) {\n return isodate.parse(val);\n }\n if (milliseconds.is(val)) {\n return milliseconds.parse(val);\n }\n if (seconds.is(val)) {\n return seconds.parse(val);\n }\n\n // fallback to Date.parse\n return new Date(val);\n};\n\n/**\n * If the number passed val is seconds from the epoch, turn it into milliseconds.\n * Milliseconds would be greater than 31557600000 (December 31, 1970).\n *\n * @param {number} num\n */\nfunction toMs(num) {\n if (num < 31557600000) return num * 1000;\n return num;\n}\n","\"use strict\";\n\n/**\n * Matcher.\n */\n\nvar matcher = /\\d{13}/;\n\n/**\n * Check whether a string is a millisecond date string.\n *\n * @param {string} string\n * @return {boolean}\n */\nexports.is = function (string) {\n return matcher.test(string);\n};\n\n/**\n * Convert a millisecond string to a date.\n *\n * @param {string} millis\n * @return {Date}\n */\nexports.parse = function (millis) {\n millis = parseInt(millis, 10);\n return new Date(millis);\n};\n","\"use strict\";\n\n/**\n * Matcher.\n */\n\nvar matcher = /\\d{10}/;\n\n/**\n * Check whether a string is a second date string.\n *\n * @param {string} string\n * @return {Boolean}\n */\nexports.is = function (string) {\n return matcher.test(string);\n};\n\n/**\n * Convert a second string to a date.\n *\n * @param {string} seconds\n * @return {Date}\n */\nexports.parse = function (seconds) {\n var millis = parseInt(seconds, 10) * 1000;\n return new Date(millis);\n};\n","\nvar identity = function(_){ return _; };\n\n\n/**\n * Module exports, export\n */\n\nmodule.exports = multiple(find);\nmodule.exports.find = module.exports;\n\n\n/**\n * Export the replacement function, return the modified object\n */\n\nmodule.exports.replace = function (obj, key, val, options) {\n multiple(replace).call(this, obj, key, val, options);\n return obj;\n};\n\n\n/**\n * Export the delete function, return the modified object\n */\n\nmodule.exports.del = function (obj, key, options) {\n multiple(del).call(this, obj, key, null, options);\n return obj;\n};\n\n\n/**\n * Compose applying the function to a nested key\n */\n\nfunction multiple (fn) {\n return function (obj, path, val, options) {\n var normalize = options && isFunction(options.normalizer) ? options.normalizer : defaultNormalize;\n path = normalize(path);\n\n var key;\n var finished = false;\n\n while (!finished) loop();\n\n function loop() {\n for (key in obj) {\n var normalizedKey = normalize(key);\n if (0 === path.indexOf(normalizedKey)) {\n var temp = path.substr(normalizedKey.length);\n if (temp.charAt(0) === '.' || temp.length === 0) {\n path = temp.substr(1);\n var child = obj[key];\n\n // we're at the end and there is nothing.\n if (null == child) {\n finished = true;\n return;\n }\n\n // we're at the end and there is something.\n if (!path.length) {\n finished = true;\n return;\n }\n\n // step into child\n obj = child;\n\n // but we're done here\n return;\n }\n }\n }\n\n key = undefined;\n // if we found no matching properties\n // on the current object, there's no match.\n finished = true;\n }\n\n if (!key) return;\n if (null == obj) return obj;\n\n // the `obj` and `key` is one above the leaf object and key, so\n // start object: { a: { 'b.c': 10 } }\n // end object: { 'b.c': 10 }\n // end key: 'b.c'\n // this way, you can do `obj[key]` and get `10`.\n return fn(obj, key, val);\n };\n}\n\n\n/**\n * Find an object by its key\n *\n * find({ first_name : 'Calvin' }, 'firstName')\n */\n\nfunction find (obj, key) {\n if (obj.hasOwnProperty(key)) return obj[key];\n}\n\n\n/**\n * Delete a value for a given key\n *\n * del({ a : 'b', x : 'y' }, 'X' }) -> { a : 'b' }\n */\n\nfunction del (obj, key) {\n if (obj.hasOwnProperty(key)) delete obj[key];\n return obj;\n}\n\n\n/**\n * Replace an objects existing value with a new one\n *\n * replace({ a : 'b' }, 'a', 'c') -> { a : 'c' }\n */\n\nfunction replace (obj, key, val) {\n if (obj.hasOwnProperty(key)) obj[key] = val;\n return obj;\n}\n\n/**\n * Normalize a `dot.separated.path`.\n *\n * A.HELL(!*&#(!)O_WOR LD.bar => ahelloworldbar\n *\n * @param {String} path\n * @return {String}\n */\n\nfunction defaultNormalize(path) {\n return path.replace(/[^a-zA-Z0-9\\.]+/g, '').toLowerCase();\n}\n\n/**\n * Check if a value is a function.\n *\n * @param {*} val\n * @return {boolean} Returns `true` if `val` is a function, otherwise `false`.\n */\n\nfunction isFunction(val) {\n return typeof val === 'function';\n}\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n\nfunction emptyFunction() {}\nfunction emptyFunctionWithReset() {}\nemptyFunctionWithReset.resetWarningCache = emptyFunction;\n\nmodule.exports = function() {\n function shim(props, propName, componentName, location, propFullName, secret) {\n if (secret === ReactPropTypesSecret) {\n // It is still safe when called from React.\n return;\n }\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use PropTypes.checkPropTypes() to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n };\n shim.isRequired = shim;\n function getShim() {\n return shim;\n };\n // Important!\n // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n var ReactPropTypes = {\n array: shim,\n bigint: shim,\n bool: shim,\n func: shim,\n number: shim,\n object: shim,\n string: shim,\n symbol: shim,\n\n any: shim,\n arrayOf: getShim,\n element: shim,\n elementType: shim,\n instanceOf: getShim,\n node: shim,\n objectOf: getShim,\n oneOf: getShim,\n oneOfType: getShim,\n shape: getShim,\n exact: getShim,\n\n checkPropTypes: emptyFunctionWithReset,\n resetWarningCache: emptyFunction\n };\n\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nif (process.env.NODE_ENV !== 'production') {\n var ReactIs = require('react-is');\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);\n} else {\n // By explicitly using `prop-types` you are opting into new production behavior.\n // http://fb.me/prop-types-in-prod\n module.exports = require('./factoryWithThrowingShims')();\n}\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n","'use strict'\nfunction tryStringify (o) {\n try { return JSON.stringify(o) } catch(e) { return '\"[Circular]\"' }\n}\n\nmodule.exports = format\n\nfunction format(f, args, opts) {\n var ss = (opts && opts.stringify) || tryStringify\n var offset = 1\n if (typeof f === 'object' && f !== null) {\n var len = args.length + offset\n if (len === 1) return f\n var objects = new Array(len)\n objects[0] = ss(f)\n for (var index = 1; index < len; index++) {\n objects[index] = ss(args[index])\n }\n return objects.join(' ')\n }\n if (typeof f !== 'string') {\n return f\n }\n var argLen = args.length\n if (argLen === 0) return f\n var str = ''\n var a = 1 - offset\n var lastPos = -1\n var flen = (f && f.length) || 0\n for (var i = 0; i < flen;) {\n if (f.charCodeAt(i) === 37 && i + 1 < flen) {\n lastPos = lastPos > -1 ? lastPos : 0\n switch (f.charCodeAt(i + 1)) {\n case 100: // 'd'\n case 102: // 'f'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Number(args[a])\n lastPos = i + 2\n i++\n break\n case 105: // 'i'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Math.floor(Number(args[a]))\n lastPos = i + 2\n i++\n break\n case 79: // 'O'\n case 111: // 'o'\n case 106: // 'j'\n if (a >= argLen)\n break\n if (args[a] === undefined) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n var type = typeof args[a]\n if (type === 'string') {\n str += '\\'' + args[a] + '\\''\n lastPos = i + 2\n i++\n break\n }\n if (type === 'function') {\n str += args[a].name || ''\n lastPos = i + 2\n i++\n break\n }\n str += ss(args[a])\n lastPos = i + 2\n i++\n break\n case 115: // 's'\n if (a >= argLen)\n break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += String(args[a])\n lastPos = i + 2\n i++\n break\n case 37: // '%'\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += '%'\n lastPos = i + 2\n i++\n a--\n break\n }\n ++a\n }\n ++i\n }\n if (lastPos === -1)\n return f\n else if (lastPos < flen) {\n str += f.slice(lastPos)\n }\n\n return str\n}\n","/**\n * @license React\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;cb}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(ra,\nsa);z[b]=new v(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"\")&&(k=k.replace(\"\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e\"+b.valueOf().toString()+\"\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&Ng(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=Lg(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Tg(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Rg(f.type,f.key,f.props,null,a.mode,h),h.ref=Lg(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==\nd;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=Sg(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);Mg(a,f)}return\"string\"===typeof f&&\"\"!==f||\"number\"===typeof f?(f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):\n(c(a,d),d=Qg(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Ug=Og(!0),Vg=Og(!1),Wg=Uf(null),Xg=null,Yg=null,Zg=null;function $g(){Zg=Yg=Xg=null}function ah(a){var b=Wg.current;E(Wg);a._currentValue=b}function bh(a,b,c){for(;null!==a;){var d=a.alternate;(a.childLanes&b)!==b?(a.childLanes|=b,null!==d&&(d.childLanes|=b)):null!==d&&(d.childLanes&b)!==b&&(d.childLanes|=b);if(a===c)break;a=a.return}}\nfunction ch(a,b){Xg=a;Zg=Yg=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(dh=!0),a.firstContext=null)}function eh(a){var b=a._currentValue;if(Zg!==a)if(a={context:a,memoizedValue:b,next:null},null===Yg){if(null===Xg)throw Error(p(308));Yg=a;Xg.dependencies={lanes:0,firstContext:a}}else Yg=Yg.next=a;return b}var fh=null;function gh(a){null===fh?fh=[a]:fh.push(a)}\nfunction hh(a,b,c,d){var e=b.interleaved;null===e?(c.next=c,gh(b)):(c.next=e.next,e.next=c);b.interleaved=c;return ih(a,d)}function ih(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}var jh=!1;function kh(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}\nfunction lh(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function mh(a,b){return{eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}\nfunction nh(a,b,c){var d=a.updateQueue;if(null===d)return null;d=d.shared;if(0!==(K&2)){var e=d.pending;null===e?b.next=b:(b.next=e.next,e.next=b);d.pending=b;return ih(a,c)}e=d.interleaved;null===e?(b.next=b,gh(d)):(b.next=e.next,e.next=b);d.interleaved=b;return ih(a,c)}function oh(a,b,c){b=b.updateQueue;if(null!==b&&(b=b.shared,0!==(c&4194240))){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nfunction ph(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next}while(null!==c);null===f?e=f=b:f=f.next=b}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=\nb;c.lastBaseUpdate=b}\nfunction qh(a,b,c,d){var e=a.updateQueue;jh=!1;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,l=k.next;k.next=null;null===g?f=l:g.next=l;g=k;var m=a.alternate;null!==m&&(m=m.updateQueue,h=m.lastBaseUpdate,h!==g&&(null===h?m.firstBaseUpdate=l:h.next=l,m.lastBaseUpdate=k))}if(null!==f){var q=e.baseState;g=0;m=l=k=null;h=f;do{var r=h.lane,y=h.eventTime;if((d&r)===r){null!==m&&(m=m.next={eventTime:y,lane:0,tag:h.tag,payload:h.payload,callback:h.callback,\nnext:null});a:{var n=a,t=h;r=b;y=c;switch(t.tag){case 1:n=t.payload;if(\"function\"===typeof n){q=n.call(y,q,r);break a}q=n;break a;case 3:n.flags=n.flags&-65537|128;case 0:n=t.payload;r=\"function\"===typeof n?n.call(y,q,r):n;if(null===r||void 0===r)break a;q=A({},q,r);break a;case 2:jh=!0}}null!==h.callback&&0!==h.lane&&(a.flags|=64,r=e.effects,null===r?e.effects=[h]:r.push(h))}else y={eventTime:y,lane:r,tag:h.tag,payload:h.payload,callback:h.callback,next:null},null===m?(l=m=y,k=q):m=m.next=y,g|=r;\nh=h.next;if(null===h)if(h=e.shared.pending,null===h)break;else r=h,h=r.next,r.next=null,e.lastBaseUpdate=r,e.shared.pending=null}while(1);null===m&&(k=q);e.baseState=k;e.firstBaseUpdate=l;e.lastBaseUpdate=m;b=e.shared.interleaved;if(null!==b){e=b;do g|=e.lane,e=e.next;while(e!==b)}else null===f&&(e.shared.lanes=0);rh|=g;a.lanes=g;a.memoizedState=q}}\nfunction sh(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;bc?c:4;a(!0);var d=Gh.transition;Gh.transition={};try{a(!1),b()}finally{C=c,Gh.transition=d}}function wi(){return Uh().memoizedState}\nfunction xi(a,b,c){var d=yi(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,c);else if(c=hh(a,b,c,d),null!==c){var e=R();gi(c,a,d,e);Bi(c,b,d)}}\nfunction ii(a,b,c){var d=yi(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,gh(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=hh(a,b,e,d);null!==c&&(e=R(),gi(c,a,d,e),Bi(c,b,d))}}\nfunction zi(a){var b=a.alternate;return a===M||null!==b&&b===M}function Ai(a,b){Jh=Ih=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Bi(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nvar Rh={readContext:eh,useCallback:P,useContext:P,useEffect:P,useImperativeHandle:P,useInsertionEffect:P,useLayoutEffect:P,useMemo:P,useReducer:P,useRef:P,useState:P,useDebugValue:P,useDeferredValue:P,useTransition:P,useMutableSource:P,useSyncExternalStore:P,useId:P,unstable_isNewReconciler:!1},Oh={readContext:eh,useCallback:function(a,b){Th().memoizedState=[a,void 0===b?null:b];return a},useContext:eh,useEffect:mi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ki(4194308,\n4,pi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ki(4194308,4,a,b)},useInsertionEffect:function(a,b){return ki(4,2,a,b)},useMemo:function(a,b){var c=Th();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=Th();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=xi.bind(null,M,a);return[d.memoizedState,a]},useRef:function(a){var b=\nTh();a={current:a};return b.memoizedState=a},useState:hi,useDebugValue:ri,useDeferredValue:function(a){return Th().memoizedState=a},useTransition:function(){var a=hi(!1),b=a[0];a=vi.bind(null,a[1]);Th().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=M,e=Th();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===Q)throw Error(p(349));0!==(Hh&30)||di(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;mi(ai.bind(null,d,\nf,a),[a]);d.flags|=2048;bi(9,ci.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Th(),b=Q.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=\":\"+b+\"R\"+c;c=Kh++;0\\x3c/script>\",a=a.removeChild(a.firstChild)):\n\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;zj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case \"dialog\":D(\"cancel\",a);D(\"close\",a);e=d;break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;eGj&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304)}else{if(!d)if(a=Ch(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Dj(f,!0),null===f.tail&&\"hidden\"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Gj&&1073741824!==c&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=\nb,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=L.current,G(L,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Hj(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(fj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}\nfunction Ij(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return zh(),E(Wf),E(H),Eh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Bh(b),null;case 13:E(L);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(L),null;case 4:return zh(),null;case 10:return ah(b.type._context),null;case 22:case 23:return Hj(),\nnull;case 24:return null;default:return null}}var Jj=!1,U=!1,Kj=\"function\"===typeof WeakSet?WeakSet:Set,V=null;function Lj(a,b){var c=a.ref;if(null!==c)if(\"function\"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Mj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Nj=!1;\nfunction Oj(a,b){Cf=dd;a=Me();if(Ne(a)){if(\"selectionStart\"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=\nq.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;\ncase 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Ci(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent=\"\":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Nj;Nj=!1;return n}\nfunction Pj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Mj(b,c,f)}e=e.next}while(e!==d)}}function Qj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Rj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}\"function\"===typeof b?b(a):b.current=a}}\nfunction Sj(a){var b=a.alternate;null!==b&&(a.alternate=null,Sj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Tj(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction Uj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Tj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}\nfunction Vj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Vj(a,b,c),a=a.sibling;null!==a;)Vj(a,b,c),a=a.sibling}\nfunction Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}var X=null,Xj=!1;function Yj(a,b,c){for(c=c.child;null!==c;)Zj(a,b,c),c=c.sibling}\nfunction Zj(a,b,c){if(lc&&\"function\"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Lj(c,b);case 6:var d=X,e=Xj;X=null;Yj(a,b,c);X=d;Xj=e;null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Xj;X=c.stateNode.containerInfo;Xj=!0;\nYj(a,b,c);X=d;Xj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Mj(c,b,g):0!==(f&4)&&Mj(c,b,g));e=e.next}while(e!==d)}Yj(a,b,c);break;case 1:if(!U&&(Lj(c,b),d=c.stateNode,\"function\"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Yj(a,b,c);break;case 21:Yj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==\nc.memoizedState,Yj(a,b,c),U=d):Yj(a,b,c);break;default:Yj(a,b,c)}}function ak(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Kj);b.forEach(function(b){var d=bk.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction ck(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*lk(d/1960))-d;if(10a?16:a;if(null===wk)var d=!1;else{a=wk;wk=null;xk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-fk?Kk(a,0):rk|=c);Dk(a,b)}function Yk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=R();a=ih(a,b);null!==a&&(Ac(a,b,c),Dk(a,c))}function uj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Yk(a,c)}\nfunction bk(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Yk(a,c)}var Vk;\nVk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)dh=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return dh=!1,yj(a,b,c);dh=0!==(a.flags&131072)?!0:!1}else dh=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;ij(a,b);a=b.pendingProps;var e=Yf(b,H.current);ch(b,c);e=Nh(null,b,d,a,e,c);var f=Sh();b.flags|=1;\"object\"===typeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=\nnull,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,kh(b),e.updater=Ei,b.stateNode=e,e._reactInternals=b,Ii(b,d,a,c),b=jj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Xi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{ij(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Zk(d);a=Ci(d,a);switch(e){case 0:b=cj(null,b,d,a,c);break a;case 1:b=hj(null,b,d,a,c);break a;case 11:b=Yi(null,b,d,a,c);break a;case 14:b=$i(null,b,d,Ci(d.type,a),c);break a}throw Error(p(306,\nd,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),cj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),hj(a,b,d,e,c);case 3:a:{kj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;lh(a,b);qh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=\nf,b.memoizedState=f,b.flags&256){e=Ji(Error(p(423)),b);b=lj(a,b,d,c,e);break a}else if(d!==e){e=Ji(Error(p(424)),b);b=lj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Vg(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=Zi(a,b,c);break a}Xi(a,b,d,c)}b=b.child}return b;case 5:return Ah(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),\ngj(a,b),Xi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return oj(a,b,c);case 4:return yh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Ug(b,null,d,c):Xi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),Yi(a,b,d,e,c);case 7:return Xi(a,b,b.pendingProps,c),b.child;case 8:return Xi(a,b,b.pendingProps.children,c),b.child;case 12:return Xi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;\ng=e.value;G(Wg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=Zi(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=mh(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);bh(f.return,\nc,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);bh(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Xi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,ch(b,c),e=eh(e),d=d(e),b.flags|=1,Xi(a,b,d,c),\nb.child;case 14:return d=b.type,e=Ci(d,b.pendingProps),e=Ci(d.type,e),$i(a,b,d,e,c);case 15:return bj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),ij(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,ch(b,c),Gi(b,d,e),Ii(b,d,e,c),jj(null,b,d,!0,a,c);case 19:return xj(a,b,c);case 22:return dj(a,b,c)}throw Error(p(156,b.tag));};function Fk(a,b){return ac(a,b)}\nfunction $k(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new $k(a,b,c,d)}function aj(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction Zk(a){if(\"function\"===typeof a)return aj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}\nfunction Pg(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};\nc.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}\nfunction Rg(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)aj(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ya:return Tg(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return pj(c,e,f,b);default:if(\"object\"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;\nbreak a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,\"\"));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Tg(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function pj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function Qg(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}\nfunction Sg(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}\nfunction al(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=\nnull}function bl(a,b,c,d,e,f,g,h,k){a=new al(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};kh(f);return a}function cl(a,b,c){var d=3>>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","var toPropertyKey = require(\"./toPropertyKey.js\");\nfunction _defineProperty(e, r, t) {\n return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n value: t,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }) : e[r] = t, e;\n}\nmodule.exports = _defineProperty, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","var _typeof = require(\"./typeof.js\")[\"default\"];\nfunction toPrimitive(t, r) {\n if (\"object\" != _typeof(t) || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r || \"default\");\n if (\"object\" != _typeof(i)) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\nmodule.exports = toPrimitive, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","var _typeof = require(\"./typeof.js\")[\"default\"];\nvar toPrimitive = require(\"./toPrimitive.js\");\nfunction toPropertyKey(t) {\n var i = toPrimitive(t, \"string\");\n return \"symbol\" == _typeof(i) ? i : i + \"\";\n}\nmodule.exports = toPropertyKey, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return module.exports = _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports, _typeof(o);\n}\nmodule.exports = _typeof, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","'use strict'\n\nconst format = require('quick-format-unescaped')\n\nmodule.exports = pino\n\nconst _console = pfGlobalThisOrFallback().console || {}\nconst stdSerializers = {\n mapHttpRequest: mock,\n mapHttpResponse: mock,\n wrapRequestSerializer: passthrough,\n wrapResponseSerializer: passthrough,\n wrapErrorSerializer: passthrough,\n req: mock,\n res: mock,\n err: asErrValue,\n errWithCause: asErrValue\n}\nfunction levelToValue (level, logger) {\n return level === 'silent'\n ? Infinity\n : logger.levels.values[level]\n}\nconst baseLogFunctionSymbol = Symbol('pino.logFuncs')\nconst hierarchySymbol = Symbol('pino.hierarchy')\n\nconst logFallbackMap = {\n error: 'log',\n fatal: 'error',\n warn: 'error',\n info: 'log',\n debug: 'log',\n trace: 'log'\n}\n\nfunction appendChildLogger (parentLogger, childLogger) {\n const newEntry = {\n logger: childLogger,\n parent: parentLogger[hierarchySymbol]\n }\n childLogger[hierarchySymbol] = newEntry\n}\n\nfunction setupBaseLogFunctions (logger, levels, proto) {\n const logFunctions = {}\n levels.forEach(level => {\n logFunctions[level] = proto[level] ? proto[level] : (_console[level] || _console[logFallbackMap[level] || 'log'] || noop)\n })\n logger[baseLogFunctionSymbol] = logFunctions\n}\n\nfunction shouldSerialize (serialize, serializers) {\n if (Array.isArray(serialize)) {\n const hasToFilter = serialize.filter(function (k) {\n return k !== '!stdSerializers.err'\n })\n return hasToFilter\n } else if (serialize === true) {\n return Object.keys(serializers)\n }\n\n return false\n}\n\nfunction pino (opts) {\n opts = opts || {}\n opts.browser = opts.browser || {}\n\n const transmit = opts.browser.transmit\n if (transmit && typeof transmit.send !== 'function') { throw Error('pino: transmit option must have a send function') }\n\n const proto = opts.browser.write || _console\n if (opts.browser.write) opts.browser.asObject = true\n const serializers = opts.serializers || {}\n const serialize = shouldSerialize(opts.browser.serialize, serializers)\n let stdErrSerialize = opts.browser.serialize\n\n if (\n Array.isArray(opts.browser.serialize) &&\n opts.browser.serialize.indexOf('!stdSerializers.err') > -1\n ) stdErrSerialize = false\n\n const customLevels = Object.keys(opts.customLevels || {})\n const levels = ['error', 'fatal', 'warn', 'info', 'debug', 'trace'].concat(customLevels)\n\n if (typeof proto === 'function') {\n levels.forEach(function (level) {\n proto[level] = proto\n })\n }\n if (opts.enabled === false || opts.browser.disabled) opts.level = 'silent'\n const level = opts.level || 'info'\n const logger = Object.create(proto)\n if (!logger.log) logger.log = noop\n\n setupBaseLogFunctions(logger, levels, proto)\n // setup root hierarchy entry\n appendChildLogger({}, logger)\n\n Object.defineProperty(logger, 'levelVal', {\n get: getLevelVal\n })\n Object.defineProperty(logger, 'level', {\n get: getLevel,\n set: setLevel\n })\n\n const setOpts = {\n transmit,\n serialize,\n asObject: opts.browser.asObject,\n formatters: opts.browser.formatters,\n levels,\n timestamp: getTimeFunction(opts),\n messageKey: opts.messageKey || 'msg',\n onChild: opts.onChild || noop\n }\n logger.levels = getLevels(opts)\n logger.level = level\n\n logger.setMaxListeners = logger.getMaxListeners =\n logger.emit = logger.addListener = logger.on =\n logger.prependListener = logger.once =\n logger.prependOnceListener = logger.removeListener =\n logger.removeAllListeners = logger.listeners =\n logger.listenerCount = logger.eventNames =\n logger.write = logger.flush = noop\n logger.serializers = serializers\n logger._serialize = serialize\n logger._stdErrSerialize = stdErrSerialize\n logger.child = function (...args) { return child.call(this, setOpts, ...args) }\n\n if (transmit) logger._logEvent = createLogEventShape()\n\n function getLevelVal () {\n return levelToValue(this.level, this)\n }\n\n function getLevel () {\n return this._level\n }\n function setLevel (level) {\n if (level !== 'silent' && !this.levels.values[level]) {\n throw Error('unknown level ' + level)\n }\n this._level = level\n\n set(this, setOpts, logger, 'error') // <-- must stay first\n set(this, setOpts, logger, 'fatal')\n set(this, setOpts, logger, 'warn')\n set(this, setOpts, logger, 'info')\n set(this, setOpts, logger, 'debug')\n set(this, setOpts, logger, 'trace')\n\n customLevels.forEach((level) => {\n set(this, setOpts, logger, level)\n })\n }\n\n function child (setOpts, bindings, childOptions) {\n if (!bindings) {\n throw new Error('missing bindings for child Pino')\n }\n childOptions = childOptions || {}\n if (serialize && bindings.serializers) {\n childOptions.serializers = bindings.serializers\n }\n const childOptionsSerializers = childOptions.serializers\n if (serialize && childOptionsSerializers) {\n var childSerializers = Object.assign({}, serializers, childOptionsSerializers)\n var childSerialize = opts.browser.serialize === true\n ? Object.keys(childSerializers)\n : serialize\n delete bindings.serializers\n applySerializers([bindings], childSerialize, childSerializers, this._stdErrSerialize)\n }\n function Child (parent) {\n this._childLevel = (parent._childLevel | 0) + 1\n\n // make sure bindings are available in the `set` function\n this.bindings = bindings\n\n if (childSerializers) {\n this.serializers = childSerializers\n this._serialize = childSerialize\n }\n if (transmit) {\n this._logEvent = createLogEventShape(\n [].concat(parent._logEvent.bindings, bindings)\n )\n }\n }\n Child.prototype = this\n const newLogger = new Child(this)\n\n // must happen before the level is assigned\n appendChildLogger(this, newLogger)\n newLogger.child = function (...args) { return child.call(this, setOpts, ...args) }\n // required to actually initialize the logger functions for any given child\n newLogger.level = childOptions.level || this.level // allow level to be set by childOptions\n setOpts.onChild(newLogger)\n\n return newLogger\n }\n return logger\n}\n\nfunction getLevels (opts) {\n const customLevels = opts.customLevels || {}\n\n const values = Object.assign({}, pino.levels.values, customLevels)\n const labels = Object.assign({}, pino.levels.labels, invertObject(customLevels))\n\n return {\n values,\n labels\n }\n}\n\nfunction invertObject (obj) {\n const inverted = {}\n Object.keys(obj).forEach(function (key) {\n inverted[obj[key]] = key\n })\n return inverted\n}\n\npino.levels = {\n values: {\n fatal: 60,\n error: 50,\n warn: 40,\n info: 30,\n debug: 20,\n trace: 10\n },\n labels: {\n 10: 'trace',\n 20: 'debug',\n 30: 'info',\n 40: 'warn',\n 50: 'error',\n 60: 'fatal'\n }\n}\n\npino.stdSerializers = stdSerializers\npino.stdTimeFunctions = Object.assign({}, { nullTime, epochTime, unixTime, isoTime })\n\nfunction getBindingChain (logger) {\n const bindings = []\n if (logger.bindings) {\n bindings.push(logger.bindings)\n }\n\n // traverse up the tree to get all bindings\n let hierarchy = logger[hierarchySymbol]\n while (hierarchy.parent) {\n hierarchy = hierarchy.parent\n if (hierarchy.logger.bindings) {\n bindings.push(hierarchy.logger.bindings)\n }\n }\n\n return bindings.reverse()\n}\n\nfunction set (self, opts, rootLogger, level) {\n // override the current log functions with either `noop` or the base log function\n Object.defineProperty(self, level, {\n value: (levelToValue(self.level, rootLogger) > levelToValue(level, rootLogger)\n ? noop\n : rootLogger[baseLogFunctionSymbol][level]),\n writable: true,\n enumerable: true,\n configurable: true\n })\n\n if (self[level] === noop) {\n if (!opts.transmit) return\n\n const transmitLevel = opts.transmit.level || self.level\n const transmitValue = levelToValue(transmitLevel, rootLogger)\n const methodValue = levelToValue(level, rootLogger)\n if (methodValue < transmitValue) return\n }\n\n // make sure the log format is correct\n self[level] = createWrap(self, opts, rootLogger, level)\n\n // prepend bindings if it is not the root logger\n const bindings = getBindingChain(self)\n if (bindings.length === 0) {\n // early exit in case for rootLogger\n return\n }\n self[level] = prependBindingsInArguments(bindings, self[level])\n}\n\nfunction prependBindingsInArguments (bindings, logFunc) {\n return function () {\n return logFunc.apply(this, [...bindings, ...arguments])\n }\n}\n\nfunction createWrap (self, opts, rootLogger, level) {\n return (function (write) {\n return function LOG () {\n const ts = opts.timestamp()\n const args = new Array(arguments.length)\n const proto = (Object.getPrototypeOf && Object.getPrototypeOf(this) === _console) ? _console : this\n for (var i = 0; i < args.length; i++) args[i] = arguments[i]\n\n var argsIsSerialized = false\n if (opts.serialize) {\n applySerializers(args, this._serialize, this.serializers, this._stdErrSerialize)\n argsIsSerialized = true\n }\n if (opts.asObject || opts.formatters) {\n write.call(proto, asObject(this, level, args, ts, opts))\n } else write.apply(proto, args)\n\n if (opts.transmit) {\n const transmitLevel = opts.transmit.level || self._level\n const transmitValue = levelToValue(transmitLevel, rootLogger)\n const methodValue = levelToValue(level, rootLogger)\n if (methodValue < transmitValue) return\n transmit(this, {\n ts,\n methodLevel: level,\n methodValue,\n transmitLevel,\n transmitValue: rootLogger.levels.values[opts.transmit.level || self._level],\n send: opts.transmit.send,\n val: levelToValue(self._level, rootLogger)\n }, args, argsIsSerialized)\n }\n }\n })(self[baseLogFunctionSymbol][level])\n}\n\nfunction asObject (logger, level, args, ts, opts) {\n const {\n level: levelFormatter,\n log: logObjectFormatter = (obj) => obj\n } = opts.formatters || {}\n const argsCloned = args.slice()\n let msg = argsCloned[0]\n const logObject = {}\n if (ts) {\n logObject.time = ts\n }\n\n if (levelFormatter) {\n const formattedLevel = levelFormatter(level, logger.levels.values[level])\n Object.assign(logObject, formattedLevel)\n } else {\n logObject.level = logger.levels.values[level]\n }\n\n let lvl = (logger._childLevel | 0) + 1\n if (lvl < 1) lvl = 1\n // deliberate, catching objects, arrays\n if (msg !== null && typeof msg === 'object') {\n while (lvl-- && typeof argsCloned[0] === 'object') {\n Object.assign(logObject, argsCloned.shift())\n }\n msg = argsCloned.length ? format(argsCloned.shift(), argsCloned) : undefined\n } else if (typeof msg === 'string') msg = format(argsCloned.shift(), argsCloned)\n if (msg !== undefined) logObject[opts.messageKey] = msg\n\n const formattedLogObject = logObjectFormatter(logObject)\n return formattedLogObject\n}\n\nfunction applySerializers (args, serialize, serializers, stdErrSerialize) {\n for (const i in args) {\n if (stdErrSerialize && args[i] instanceof Error) {\n args[i] = pino.stdSerializers.err(args[i])\n } else if (typeof args[i] === 'object' && !Array.isArray(args[i]) && serialize) {\n for (const k in args[i]) {\n if (serialize.indexOf(k) > -1 && k in serializers) {\n args[i][k] = serializers[k](args[i][k])\n }\n }\n }\n }\n}\n\nfunction transmit (logger, opts, args, argsIsSerialized = false) {\n const send = opts.send\n const ts = opts.ts\n const methodLevel = opts.methodLevel\n const methodValue = opts.methodValue\n const val = opts.val\n const bindings = logger._logEvent.bindings\n\n if (!argsIsSerialized) {\n applySerializers(\n args,\n logger._serialize || Object.keys(logger.serializers),\n logger.serializers,\n logger._stdErrSerialize === undefined ? true : logger._stdErrSerialize\n )\n }\n\n logger._logEvent.ts = ts\n logger._logEvent.messages = args.filter(function (arg) {\n // bindings can only be objects, so reference equality check via indexOf is fine\n return bindings.indexOf(arg) === -1\n })\n\n logger._logEvent.level.label = methodLevel\n logger._logEvent.level.value = methodValue\n\n send(methodLevel, logger._logEvent, val)\n\n logger._logEvent = createLogEventShape(bindings)\n}\n\nfunction createLogEventShape (bindings) {\n return {\n ts: 0,\n messages: [],\n bindings: bindings || [],\n level: { label: '', value: 0 }\n }\n}\n\nfunction asErrValue (err) {\n const obj = {\n type: err.constructor.name,\n msg: err.message,\n stack: err.stack\n }\n for (const key in err) {\n if (obj[key] === undefined) {\n obj[key] = err[key]\n }\n }\n return obj\n}\n\nfunction getTimeFunction (opts) {\n if (typeof opts.timestamp === 'function') {\n return opts.timestamp\n }\n if (opts.timestamp === false) {\n return nullTime\n }\n return epochTime\n}\n\nfunction mock () { return {} }\nfunction passthrough (a) { return a }\nfunction noop () {}\n\nfunction nullTime () { return false }\nfunction epochTime () { return Date.now() }\nfunction unixTime () { return Math.round(Date.now() / 1000.0) }\nfunction isoTime () { return new Date(Date.now()).toISOString() } // using Date.now() for testability\n\n/* eslint-disable */\n/* istanbul ignore next */\nfunction pfGlobalThisOrFallback () {\n function defd (o) { return typeof o !== 'undefined' && o }\n try {\n if (typeof globalThis !== 'undefined') return globalThis\n Object.defineProperty(Object.prototype, 'globalThis', {\n get: function () {\n delete Object.prototype.globalThis\n return (this.globalThis = this)\n },\n configurable: true\n })\n return globalThis\n } catch (e) {\n return defd(self) || defd(window) || defd(this) || {}\n }\n}\n/* eslint-enable */\n\nmodule.exports.default = pino\nmodule.exports.pino = pino\n","var IDX=256, HEX=[], BUFFER;\nwhile (IDX--) HEX[IDX] = (IDX + 256).toString(16).substring(1);\n\nexport function v4() {\n\tvar i=0, num, out='';\n\n\tif (!BUFFER || ((IDX + 16) > 256)) {\n\t\tBUFFER = Array(i=256);\n\t\twhile (i--) BUFFER[i] = 256 * Math.random() | 0;\n\t\ti = IDX = 0;\n\t}\n\n\tfor (; i < 16; i++) {\n\t\tnum = BUFFER[IDX + i];\n\t\tif (i==6) out += HEX[num & 15 | 64];\n\t\telse if (i==8) out += HEX[num & 63 | 128];\n\t\telse out += HEX[num];\n\n\t\tif (i & 1 && i > 1 && i < 11) out += '-';\n\t}\n\n\tIDX++;\n\treturn out;\n}\n","export function dset(obj, keys, val) {\n\tkeys.split && (keys=keys.split('.'));\n\tvar i=0, l=keys.length, t=obj, x, k;\n\twhile (i < l) {\n\t\tk = keys[i++];\n\t\tif (k === '__proto__' || k === 'constructor' || k === 'prototype') break;\n\t\tt = t[k] = (i === l) ? val : (typeof(x=t[k])===typeof(keys)) ? x : (keys[i]*0 !== 0 || !!~(''+keys[i]).indexOf('.')) ? {} : [];\n\t}\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\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\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, inner;\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 if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\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","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"static/js/\" + ({\"10\":\"tsub-middleware\",\"50\":\"ajs-destination\",\"104\":\"schemaFilter\",\"248\":\"auto-track\",\"521\":\"remoteMiddleware\",\"538\":\"queryString\",\"694\":\"legacyVideos\"}[chunkId] || chunkId) + \".\" + {\"10\":\"294d818e\",\"50\":\"4b044e88\",\"104\":\"3e32f9a8\",\"248\":\"8dfa8f51\",\"381\":\"e83165d0\",\"521\":\"996b34c5\",\"538\":\"35841bc8\",\"694\":\"04d504b0\"}[chunkId] + \".chunk.js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","var inProgress = {};\nvar dataWebpackPrefix = \"client:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tscript.timeout = 120;\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n// no on chunks loaded\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar chunkIds = data[0];\n\tvar moreModules = data[1];\n\tvar runtime = data[2];\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkclient\"] = self[\"webpackChunkclient\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","/*! js-cookie v3.0.5 | MIT */\n/* eslint-disable no-var */\nfunction assign (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n target[key] = source[key];\n }\n }\n return target\n}\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\nvar defaultConverter = {\n read: function (value) {\n if (value[0] === '\"') {\n value = value.slice(1, -1);\n }\n return value.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent)\n },\n write: function (value) {\n return encodeURIComponent(value).replace(\n /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,\n decodeURIComponent\n )\n }\n};\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\n\nfunction init (converter, defaultAttributes) {\n function set (name, value, attributes) {\n if (typeof document === 'undefined') {\n return\n }\n\n attributes = assign({}, defaultAttributes, attributes);\n\n if (typeof attributes.expires === 'number') {\n attributes.expires = new Date(Date.now() + attributes.expires * 864e5);\n }\n if (attributes.expires) {\n attributes.expires = attributes.expires.toUTCString();\n }\n\n name = encodeURIComponent(name)\n .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n .replace(/[()]/g, escape);\n\n var stringifiedAttributes = '';\n for (var attributeName in attributes) {\n if (!attributes[attributeName]) {\n continue\n }\n\n stringifiedAttributes += '; ' + attributeName;\n\n if (attributes[attributeName] === true) {\n continue\n }\n\n // Considers RFC 6265 section 5.2:\n // ...\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n // Consume the characters of the unparsed-attributes up to,\n // not including, the first %x3B (\";\") character.\n // ...\n stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];\n }\n\n return (document.cookie =\n name + '=' + converter.write(value, name) + stringifiedAttributes)\n }\n\n function get (name) {\n if (typeof document === 'undefined' || (arguments.length && !name)) {\n return\n }\n\n // To prevent the for loop in the first place assign an empty array\n // in case there are no cookies at all.\n var cookies = document.cookie ? document.cookie.split('; ') : [];\n var jar = {};\n for (var i = 0; i < cookies.length; i++) {\n var parts = cookies[i].split('=');\n var value = parts.slice(1).join('=');\n\n try {\n var found = decodeURIComponent(parts[0]);\n jar[found] = converter.read(value, found);\n\n if (name === found) {\n break\n }\n } catch (e) {}\n }\n\n return name ? jar[name] : jar\n }\n\n return Object.create(\n {\n set,\n get,\n remove: function (name, attributes) {\n set(\n name,\n '',\n assign({}, attributes, {\n expires: -1\n })\n );\n },\n withAttributes: function (attributes) {\n return init(this.converter, assign({}, this.attributes, attributes))\n },\n withConverter: function (converter) {\n return init(assign({}, this.converter, converter), this.attributes)\n }\n },\n {\n attributes: { value: Object.freeze(defaultAttributes) },\n converter: { value: Object.freeze(converter) }\n }\n )\n}\n\nvar api = init(defaultConverter, { path: '/' });\n\nconst ACTIVE_ORG_ID_COOKIE_NAME = \"active_org_id\";\n\nlet OrgRoleStructure = /*#__PURE__*/function (OrgRoleStructure) {\n OrgRoleStructure[\"SingleRole\"] = \"single_role_in_hierarchy\";\n OrgRoleStructure[\"MultiRole\"] = \"multi_role\";\n return OrgRoleStructure;\n}({});\nconst setActiveOrgId = orgId => {\n api.set(ACTIVE_ORG_ID_COOKIE_NAME, orgId, {\n sameSite: \"lax\",\n secure: true\n });\n};\nconst getActiveOrgId = () => {\n return api.get(ACTIVE_ORG_ID_COOKIE_NAME);\n};\n\nfunction getAccessHelper(orgIdToOrgMemberInfo) {\n function isRole(orgId, role) {\n const orgMemberInfo = orgIdToOrgMemberInfo[orgId];\n if (orgMemberInfo === undefined) {\n return false;\n }\n if (orgMemberInfo.orgRoleStructure === OrgRoleStructure.MultiRole) {\n return orgMemberInfo.userAssignedRole === role || orgMemberInfo.userAssignedAdditionalRoles.includes(role);\n } else {\n return orgMemberInfo.userAssignedRole === role;\n }\n }\n function isAtLeastRole(orgId, role) {\n const orgMemberInfo = orgIdToOrgMemberInfo[orgId];\n if (orgMemberInfo === undefined) {\n return false;\n }\n if (orgMemberInfo.orgRoleStructure === OrgRoleStructure.MultiRole) {\n return orgMemberInfo.userAssignedRole === role || orgMemberInfo.userAssignedAdditionalRoles.includes(role);\n } else {\n return orgMemberInfo.userInheritedRolesPlusCurrentRole.includes(role);\n }\n }\n function hasPermission(orgId, permission) {\n const orgMemberInfo = orgIdToOrgMemberInfo[orgId];\n if (orgMemberInfo === undefined) {\n return false;\n }\n return orgMemberInfo.userPermissions.includes(permission);\n }\n function hasAllPermissions(orgId, permissions) {\n const orgMemberInfo = orgIdToOrgMemberInfo[orgId];\n if (orgMemberInfo === undefined) {\n return false;\n }\n return permissions.every(permission => orgMemberInfo.userPermissions.includes(permission));\n }\n function getAccessHelperWithOrgId(orgId) {\n return {\n isRole(role) {\n return isRole(orgId, role);\n },\n isAtLeastRole(role) {\n return isAtLeastRole(orgId, role);\n },\n hasPermission(permission) {\n return hasPermission(orgId, permission);\n },\n hasAllPermissions(permissions) {\n return hasAllPermissions(orgId, permissions);\n }\n };\n }\n return {\n isRole,\n isAtLeastRole,\n hasPermission,\n hasAllPermissions,\n getAccessHelperWithOrgId\n };\n}\n\nfunction getOrgHelper(orgIdToOrgMemberInfo) {\n return {\n getOrg(orgId) {\n if (orgIdToOrgMemberInfo.hasOwnProperty(orgId)) {\n return orgIdToOrgMemberInfo[orgId];\n } else {\n return undefined;\n }\n },\n getOrgIds() {\n return Object.keys(orgIdToOrgMemberInfo);\n },\n getOrgs() {\n return Object.values(orgIdToOrgMemberInfo);\n },\n getOrgByName(orgName) {\n for (const orgMemberInfo of Object.values(orgIdToOrgMemberInfo)) {\n if (orgMemberInfo.orgName === orgName || orgMemberInfo.urlSafeOrgName === orgName) {\n return orgMemberInfo;\n }\n }\n return undefined;\n }\n };\n}\n\nclass UserClass {\n // Metadata about the user\n\n // If you used our migration APIs to migrate this user from a different system,\n // this is their original ID from that system.\n\n constructor(userFields, orgIdToUserOrgInfo) {\n this.userId = userFields.userId;\n this.orgIdToUserOrgInfo = orgIdToUserOrgInfo;\n this.email = userFields.email;\n this.firstName = userFields.firstName;\n this.lastName = userFields.lastName;\n this.username = userFields.username;\n this.createdAt = userFields.createdAt;\n this.pictureUrl = userFields.pictureUrl;\n this.hasPassword = userFields.hasPassword;\n this.hasMfaEnabled = userFields.hasMfaEnabled;\n this.canCreateOrgs = userFields.canCreateOrgs;\n this.legacyUserId = userFields.legacyUserId;\n this.impersonatorUserId = userFields.impersonatorUserId;\n this.properties = userFields.properties;\n }\n getOrg(orgId) {\n if (!this.orgIdToUserOrgInfo) {\n return undefined;\n }\n return this.orgIdToUserOrgInfo[orgId];\n }\n getOrgByName(orgName) {\n if (!this.orgIdToUserOrgInfo) {\n return undefined;\n }\n const urlSafeOrgName = orgName.toLowerCase().replace(/ /g, \"-\");\n for (const orgId in this.orgIdToUserOrgInfo) {\n const orgMemberInfo = this.orgIdToUserOrgInfo[orgId];\n if ((orgMemberInfo === null || orgMemberInfo === void 0 ? void 0 : orgMemberInfo.urlSafeOrgName) === urlSafeOrgName) {\n return orgMemberInfo;\n }\n }\n return undefined;\n }\n getUserProperty(key) {\n if (!this.properties) {\n return undefined;\n }\n return this.properties[key];\n }\n getOrgs() {\n if (!this.orgIdToUserOrgInfo) {\n return [];\n }\n return Object.values(this.orgIdToUserOrgInfo);\n }\n isImpersonating() {\n return !!this.impersonatorUserId;\n }\n isRole(orgId, role) {\n const orgMemberInfo = this.getOrg(orgId);\n if (!orgMemberInfo) {\n return false;\n }\n return orgMemberInfo.isRole(role);\n }\n isAtLeastRole(orgId, role) {\n const orgMemberInfo = this.getOrg(orgId);\n if (!orgMemberInfo) {\n return false;\n }\n return orgMemberInfo.isAtLeastRole(role);\n }\n hasPermission(orgId, permission) {\n const orgMemberInfo = this.getOrg(orgId);\n if (!orgMemberInfo) {\n return false;\n }\n return orgMemberInfo.hasPermission(permission);\n }\n hasAllPermissions(orgId, permissions) {\n const orgMemberInfo = this.getOrg(orgId);\n if (!orgMemberInfo) {\n return false;\n }\n return orgMemberInfo.hasAllPermissions(permissions);\n }\n static fromJSON(json) {\n const obj = JSON.parse(json);\n const orgIdToUserOrgInfo = {};\n for (const orgId in obj.orgIdToUserOrgInfo) {\n orgIdToUserOrgInfo[orgId] = OrgMemberInfoClass.fromJSON(JSON.stringify(obj.orgIdToUserOrgInfo[orgId]));\n }\n try {\n return new UserClass({\n userId: obj.userId,\n email: obj.email,\n createdAt: obj.createdAt,\n firstName: obj.firstName,\n lastName: obj.lastName,\n username: obj.username,\n legacyUserId: obj.legacyUserId,\n impersonatorUserId: obj.impersonatorUserId,\n properties: obj.properties,\n pictureUrl: obj.pictureUrl,\n hasPassword: obj.hasPassword,\n hasMfaEnabled: obj.hasMfaEnabled,\n canCreateOrgs: obj.canCreateOrgs\n }, orgIdToUserOrgInfo);\n } catch (e) {\n console.error(\"Unable to parse User. Make sure the JSON string is a stringified `UserClass` type.\", e);\n throw e;\n }\n }\n}\nclass OrgMemberInfoClass {\n constructor(orgId, orgName, orgMetadata, urlSafeOrgName, userAssignedRole, userInheritedRolesPlusCurrentRole, userPermissions, orgRoleStructure, userAssignedAdditionalRoles) {\n this.orgId = orgId;\n this.orgName = orgName;\n this.orgMetadata = orgMetadata;\n this.urlSafeOrgName = urlSafeOrgName;\n this.orgRoleStructure = orgRoleStructure !== null && orgRoleStructure !== void 0 ? orgRoleStructure : OrgRoleStructure.SingleRole;\n this.userAssignedRole = userAssignedRole;\n this.userInheritedRolesPlusCurrentRole = userInheritedRolesPlusCurrentRole;\n this.userPermissions = userPermissions;\n this.userAssignedAdditionalRoles = userAssignedAdditionalRoles !== null && userAssignedAdditionalRoles !== void 0 ? userAssignedAdditionalRoles : [];\n }\n\n // validation methods\n isRole(role) {\n if (this.orgRoleStructure === OrgRoleStructure.MultiRole) {\n return this.userAssignedRole === role || this.userAssignedAdditionalRoles.includes(role);\n } else {\n return this.userAssignedRole === role;\n }\n }\n isAtLeastRole(role) {\n if (this.orgRoleStructure === OrgRoleStructure.MultiRole) {\n return this.userAssignedRole === role || this.userAssignedAdditionalRoles.includes(role);\n } else {\n return this.userInheritedRolesPlusCurrentRole.includes(role);\n }\n }\n hasPermission(permission) {\n return this.userPermissions.includes(permission);\n }\n hasAllPermissions(permissions) {\n return permissions.every(permission => this.hasPermission(permission));\n }\n static fromJSON(json) {\n const obj = JSON.parse(json);\n try {\n return new OrgMemberInfoClass(obj.orgId, obj.orgName, obj.orgMetadata, obj.urlSafeOrgName, obj.userAssignedRole, obj.userInheritedRolesPlusCurrentRole, obj.userPermissions, obj.orgRoleStructure, obj.userAssignedAdditionalRoles);\n } catch (e) {\n console.error(\"Unable to parse UserOrgInfo. Make sure the JSON string is a stringified `UserOrgInfo` type.\", e);\n throw e;\n }\n }\n}\nfunction convertOrgIdToOrgMemberInfo(orgIdToOrgMemberInfo) {\n if (orgIdToOrgMemberInfo === undefined) {\n return undefined;\n }\n const orgIdToUserOrgInfo = {};\n for (const orgMemberInfo of Object.values(orgIdToOrgMemberInfo)) {\n orgIdToUserOrgInfo[orgMemberInfo.orgId] = new OrgMemberInfoClass(orgMemberInfo.orgId, orgMemberInfo.orgName, orgMemberInfo.orgMetadata, orgMemberInfo.urlSafeOrgName, orgMemberInfo.userAssignedRole, orgMemberInfo.userInheritedRolesPlusCurrentRole, orgMemberInfo.userPermissions, orgMemberInfo.orgRoleStructure, orgMemberInfo.userAssignedAdditionalRoles);\n }\n return orgIdToUserOrgInfo;\n}\n\nfunction fetchAuthenticationInfo(authUrl, activeOrgId) {\n const queryParams = new URLSearchParams();\n if (activeOrgId) {\n queryParams.append(\"active_org_id\", activeOrgId);\n }\n let path = `${authUrl}/api/v1/refresh_token`;\n if (queryParams.toString()) {\n path += `?${queryParams.toString()}`;\n }\n return fetch(path, {\n method: \"GET\",\n credentials: \"include\",\n headers: {\n \"Content-Type\": \"application/json\"\n }\n }).then(res => {\n if (res.status === 401) {\n return null;\n } else if (res.status === 0) {\n logCorsError();\n return Promise.reject({\n status: 503,\n message: \"Unable to process authentication response\"\n });\n } else if (!res.ok) {\n return Promise.reject({\n status: res.status,\n message: res.statusText\n });\n } else {\n return parseResponse(res);\n }\n });\n}\nfunction logout(authUrl) {\n return fetch(`${authUrl}/api/v1/logout`, {\n method: \"POST\",\n credentials: \"include\",\n headers: {\n \"Content-Type\": \"application/json\"\n }\n }).then(res => {\n if (res.status === 0) {\n logCorsError();\n return Promise.reject({\n status: 503,\n message: \"Unable to process authentication response\"\n });\n } else if (!res.ok) {\n console.error(\"Logout error\", res.status, res.statusText);\n return Promise.reject({\n status: res.status,\n message: res.statusText\n });\n } else {\n return res.json();\n }\n });\n}\nfunction parseResponse(res) {\n return res.text().then(httpResponse => {\n try {\n const authInfoWithoutUserClass = parseJsonConvertingSnakeToCamel(httpResponse);\n return withExtraArgs(authInfoWithoutUserClass);\n } catch (e) {\n console.error(\"Unable to process authentication response\", e);\n return Promise.reject({\n status: 500,\n message: \"Unable to process authentication response\"\n });\n }\n }, e => {\n console.error(\"Unable to process authentication response\", e);\n return Promise.reject({\n status: 500,\n message: \"Unable to process authentication response\"\n });\n });\n}\n\n// The API responds with snake_case, but TypeScript convention is camelCase.\n// When parsing JSON, we pass in reviver function to convert from snake_case to camelCase.\nfunction parseJsonConvertingSnakeToCamel(str) {\n return JSON.parse(str, function (key, value) {\n if (key === \"org_id\") {\n this.orgId = value;\n } else if (key === \"org_name\") {\n this.orgName = value;\n } else if (key === \"org_metadata\") {\n this.orgMetadata = value;\n } else if (key === \"url_safe_org_name\") {\n this.urlSafeOrgName = value;\n } else if (key === \"user_role\") {\n this.userAssignedRole = value;\n } else if (key === \"inherited_user_roles_plus_current_role\") {\n this.userInheritedRolesPlusCurrentRole = value;\n } else if (key === \"user_permissions\") {\n this.userPermissions = value;\n } else if (key === \"access_token\") {\n this.accessToken = value;\n } else if (key === \"expires_at_seconds\") {\n this.expiresAtSeconds = value;\n } else if (key === \"org_id_to_org_member_info\") {\n this.orgIdToOrgMemberInfo = value;\n } else if (key === \"user_id\") {\n this.userId = value;\n } else if (key === \"email_confirmed\") {\n this.emailConfirmed = value;\n } else if (key === \"first_name\") {\n this.firstName = value;\n } else if (key === \"last_name\") {\n this.lastName = value;\n } else if (key === \"picture_url\") {\n this.pictureUrl = value;\n } else if (key === \"mfa_enabled\") {\n this.mfaEnabled = value;\n } else if (key === \"has_password\") {\n this.hasPassword = value;\n } else if (key === \"can_create_orgs\") {\n this.canCreateOrgs = value;\n } else if (key === \"created_at\") {\n this.createdAt = value;\n } else if (key === \"last_active_at\") {\n this.lastActiveAt = value;\n } else if (key === \"legacy_user_id\") {\n this.legacyUserId = value;\n } else if (key === \"impersonator_user\") {\n this.impersonatorUserId = value;\n } else if (key === \"org_role_structure\") {\n this.orgRoleStructure = value;\n } else if (key === \"additional_roles\") {\n this.userAssignedAdditionalRoles = value;\n } else {\n return value;\n }\n });\n}\nfunction withExtraArgs(authInfoWithoutExtraArgs) {\n if (authInfoWithoutExtraArgs.orgIdToOrgMemberInfo) {\n authInfoWithoutExtraArgs.orgHelper = getOrgHelper(authInfoWithoutExtraArgs.orgIdToOrgMemberInfo);\n authInfoWithoutExtraArgs.accessHelper = getAccessHelper(authInfoWithoutExtraArgs.orgIdToOrgMemberInfo);\n }\n authInfoWithoutExtraArgs.userClass = new UserClass({\n userId: authInfoWithoutExtraArgs.user.userId,\n email: authInfoWithoutExtraArgs.user.email,\n createdAt: authInfoWithoutExtraArgs.user.createdAt,\n firstName: authInfoWithoutExtraArgs.user.firstName,\n lastName: authInfoWithoutExtraArgs.user.lastName,\n username: authInfoWithoutExtraArgs.user.username,\n properties: authInfoWithoutExtraArgs.user.properties,\n pictureUrl: authInfoWithoutExtraArgs.user.pictureUrl,\n hasPassword: authInfoWithoutExtraArgs.user.hasPassword,\n hasMfaEnabled: authInfoWithoutExtraArgs.user.mfaEnabled,\n canCreateOrgs: authInfoWithoutExtraArgs.user.canCreateOrgs,\n legacyUserId: authInfoWithoutExtraArgs.user.legacyUserId,\n impersonatorUserId: authInfoWithoutExtraArgs.impersonatorUserId\n }, convertOrgIdToOrgMemberInfo(authInfoWithoutExtraArgs.orgIdToOrgMemberInfo));\n return Promise.resolve(authInfoWithoutExtraArgs);\n}\nfunction logCorsError() {\n console.error(\"Request to PropelAuth failed due to a CORS error. There are a few likely causes: \\n\" + \" 1. In the Frontend Integration section of your dashboard, make sure your requests are coming either the specified Application URL or localhost with a matching port.\\n\" + \" 2. Make sure your server is hosted on HTTPS in production.\");\n}\n\nconst DEFAULT_RETRIES = 3;\nconst runWithRetriesOnAnyError = async fn => {\n return runWithRetriesInner(fn, DEFAULT_RETRIES);\n};\nconst runWithRetriesInner = async (fn, numRetriesLeft) => {\n try {\n return await fn();\n } catch (e) {\n if (numRetriesLeft <= 0) {\n throw e;\n }\n await delay(numRetriesLeftToDelay(numRetriesLeft));\n return runWithRetriesInner(fn, numRetriesLeft - 1);\n }\n};\nconst delay = ms => new Promise(resolve => setTimeout(resolve, ms));\nconst numRetriesLeftToDelay = numRetriesLeft => {\n // We could be fancy, but we only retry 3 times so...\n if (numRetriesLeft >= 3) {\n return 100;\n } else if (numRetriesLeft === 2) {\n return 200;\n } else {\n return 300;\n }\n};\n\nfunction currentTimeSeconds() {\n return Date.now() / 1000;\n}\nfunction hasLocalStorage() {\n return typeof localStorage !== \"undefined\";\n}\nfunction hasWindow() {\n return typeof window !== \"undefined\";\n}\nfunction getLocalStorageNumber(key) {\n if (!hasLocalStorage()) {\n return null;\n }\n const value = localStorage.getItem(key);\n if (!value) {\n return null;\n }\n const num = parseInt(value, 10);\n if (Number.isNaN(num)) {\n return null;\n }\n return num;\n}\n\nconst LOGGED_IN_AT_KEY = \"__PROPEL_AUTH_LOGGED_IN_AT\";\nconst LOGGED_OUT_AT_KEY = \"__PROPEL_AUTH_LOGGED_OUT_AT\";\nconst AUTH_TOKEN_REFRESH_BEFORE_EXPIRATION_SECONDS = 10 * 60;\nconst DEBOUNCE_DURATION_FOR_REFOCUS_SECONDS = 60;\nconst ACTIVE_ORG_ACCESS_TOKEN_REFRESH_EXPIRATION_SECONDS = 60 * 5;\nconst encodeBase64 = str => {\n const encode = window ? window.btoa : btoa;\n return encode(str);\n};\nfunction validateAndCleanupOptions(authOptions) {\n try {\n // This helps make sure we have a consistent URL ignoring things like trailing slashes\n const authUrl = new URL(authOptions.authUrl);\n authOptions.authUrl = authUrl.origin;\n } catch (e) {\n console.error(\"Invalid authUrl\", e);\n throw new Error(\"Unable to initialize auth client\");\n }\n if (authOptions.enableBackgroundTokenRefresh === undefined) {\n authOptions.enableBackgroundTokenRefresh = true;\n }\n}\nfunction createClient(authOptions) {\n validateAndCleanupOptions(authOptions);\n\n // Internal state\n const clientState = {\n initialLoadFinished: false,\n authenticationInfo: null,\n observers: [],\n accessTokenObservers: [],\n lastLoggedInAtMessage: getLocalStorageNumber(LOGGED_IN_AT_KEY),\n lastLoggedOutAtMessage: getLocalStorageNumber(LOGGED_OUT_AT_KEY),\n authUrl: authOptions.authUrl,\n refreshInterval: null,\n lastRefresh: null,\n accessTokenActiveOrgMap: {}\n };\n\n // Helper functions\n function notifyObservers(isLoggedIn) {\n for (let i = 0; i < clientState.observers.length; i++) {\n const observer = clientState.observers[i];\n if (observer) {\n observer(isLoggedIn);\n }\n }\n }\n function notifyObserversOfAccessTokenChange(accessToken) {\n for (let i = 0; i < clientState.accessTokenObservers.length; i++) {\n const observer = clientState.accessTokenObservers[i];\n if (observer) {\n observer(accessToken);\n }\n }\n }\n function userJustLoggedOut(accessToken, previousAccessToken) {\n // Edge case: the first time we go to the page, if we can't load the\n // auth token we should treat it as a logout event\n return !accessToken && (previousAccessToken || !clientState.initialLoadFinished);\n }\n function userJustLoggedIn(accessToken, previousAccessToken) {\n return !previousAccessToken && accessToken;\n }\n function updateLastLoggedOutAt() {\n const loggedOutAt = currentTimeSeconds();\n clientState.lastLoggedOutAtMessage = loggedOutAt;\n if (hasLocalStorage()) {\n localStorage.setItem(LOGGED_OUT_AT_KEY, String(loggedOutAt));\n }\n }\n function updateLastLoggedInAt() {\n const loggedInAt = currentTimeSeconds();\n clientState.lastLoggedInAtMessage = loggedInAt;\n if (hasLocalStorage()) {\n localStorage.setItem(LOGGED_IN_AT_KEY, String(loggedInAt));\n }\n }\n\n /**\n * Invalidates all org's access tokens.\n */\n function resetAccessTokenActiveOrgMap() {\n clientState.accessTokenActiveOrgMap = {};\n }\n function setAuthenticationInfoAndUpdateDownstream(authenticationInfo) {\n var _clientState$authenti;\n const previousAccessToken = (_clientState$authenti = clientState.authenticationInfo) === null || _clientState$authenti === void 0 ? void 0 : _clientState$authenti.accessToken;\n clientState.authenticationInfo = authenticationInfo;\n const accessToken = authenticationInfo === null || authenticationInfo === void 0 ? void 0 : authenticationInfo.accessToken;\n if (userJustLoggedOut(accessToken, previousAccessToken)) {\n notifyObservers(false);\n updateLastLoggedOutAt();\n } else if (userJustLoggedIn(accessToken, previousAccessToken)) {\n notifyObservers(true);\n updateLastLoggedInAt();\n }\n if (previousAccessToken !== accessToken) {\n notifyObserversOfAccessTokenChange(accessToken);\n }\n resetAccessTokenActiveOrgMap();\n clientState.lastRefresh = currentTimeSeconds();\n clientState.initialLoadFinished = true;\n }\n async function forceRefreshToken(returnCached) {\n try {\n // Happy case, we fetch auth info and save it\n const authenticationInfo = await runWithRetriesOnAnyError(() => fetchAuthenticationInfo(clientState.authUrl));\n setAuthenticationInfoAndUpdateDownstream(authenticationInfo);\n return authenticationInfo;\n } catch (e) {\n // If there was an error, we sometimes still want to return the value we have cached\n // (e.g. if we were prefetching), so in those cases we swallow the exception\n if (returnCached) {\n return clientState.authenticationInfo;\n } else {\n setAuthenticationInfoAndUpdateDownstream(null);\n throw e;\n }\n }\n }\n const getSignupPageUrl = options => {\n let qs = new URLSearchParams();\n let url = `${clientState.authUrl}/signup`;\n if (options) {\n const {\n postSignupRedirectUrl,\n userSignupQueryParameters\n } = options;\n if (postSignupRedirectUrl) {\n qs.set(\"rt\", encodeBase64(postSignupRedirectUrl));\n }\n if (userSignupQueryParameters) {\n Object.entries(userSignupQueryParameters).forEach(([key, value]) => {\n qs.set(key, value);\n });\n }\n }\n if (qs.toString()) {\n url += `?${qs.toString()}`;\n }\n return url;\n };\n const getLoginPageUrl = options => {\n let qs = new URLSearchParams();\n let url = `${clientState.authUrl}/login`;\n if (options) {\n const {\n postLoginRedirectUrl,\n userSignupQueryParameters\n } = options;\n if (postLoginRedirectUrl) {\n qs.set(\"rt\", encodeBase64(postLoginRedirectUrl));\n }\n if (userSignupQueryParameters) {\n Object.entries(userSignupQueryParameters).forEach(([key, value]) => {\n qs.set(key, value);\n });\n }\n }\n if (qs.toString()) {\n url += `?${qs.toString()}`;\n }\n return url;\n };\n const getAccountPageUrl = options => {\n let qs = new URLSearchParams();\n let url = `${clientState.authUrl}/account`;\n if (options) {\n const {\n redirectBackToUrl\n } = options;\n if (redirectBackToUrl) {\n qs.set(\"rt\", encodeBase64(redirectBackToUrl));\n }\n }\n if (qs.toString()) {\n url += `?${qs.toString()}`;\n }\n return url;\n };\n const getOrgPageUrl = (orgId, options) => {\n let qs = new URLSearchParams();\n let url = `${clientState.authUrl}/org`;\n if (orgId) {\n qs.set(\"id\", orgId);\n }\n if (options) {\n if (options.redirectBackToUrl) {\n qs.set(\"rt\", encodeBase64(options.redirectBackToUrl));\n }\n }\n if (qs.toString()) {\n url += `?${qs.toString()}`;\n }\n return url;\n };\n const getCreateOrgPageUrl = options => {\n let qs = new URLSearchParams();\n let url = `${clientState.authUrl}/create_org`;\n if (options) {\n const {\n redirectBackToUrl\n } = options;\n if (redirectBackToUrl) {\n qs.set(\"rt\", encodeBase64(redirectBackToUrl));\n }\n }\n if (qs.toString()) {\n url += `?${qs.toString()}`;\n }\n return url;\n };\n const getSetupSAMLPageUrl = (orgId, options) => {\n let qs = new URLSearchParams();\n if (options) {\n if (options.redirectBackToUrl) {\n qs.set(\"rt\", encodeBase64(options.redirectBackToUrl));\n }\n }\n qs.set(\"id\", orgId);\n return `${clientState.authUrl}/saml?${qs.toString()}`;\n };\n const client = {\n addLoggedInChangeObserver(loggedInChangeObserver) {\n const hasObserver = clientState.observers.includes(loggedInChangeObserver);\n if (hasObserver) {\n console.error(\"Observer has been attached already.\");\n } else if (!loggedInChangeObserver) {\n console.error(\"Cannot add a null observer\");\n } else {\n clientState.observers.push(loggedInChangeObserver);\n }\n },\n removeLoggedInChangeObserver(loggedInChangeObserver) {\n const observerIndex = clientState.observers.indexOf(loggedInChangeObserver);\n if (observerIndex === -1) {\n console.error(\"Cannot find observer to remove\");\n } else {\n clientState.observers.splice(observerIndex, 1);\n }\n },\n addAccessTokenChangeObserver(observer) {\n const hasObserver = clientState.accessTokenObservers.includes(observer);\n if (hasObserver) {\n console.error(\"Observer has been attached already.\");\n } else if (!observer) {\n console.error(\"Cannot add a null observer\");\n } else {\n clientState.accessTokenObservers.push(observer);\n }\n },\n removeAccessTokenChangeObserver(observer) {\n const observerIndex = clientState.accessTokenObservers.indexOf(observer);\n if (observerIndex === -1) {\n console.error(\"Cannot find observer to remove\");\n } else {\n clientState.accessTokenObservers.splice(observerIndex, 1);\n }\n },\n async getAuthenticationInfoOrNull(forceRefresh) {\n const currentTimeSecs = currentTimeSeconds();\n if (forceRefresh) {\n return await forceRefreshToken(false);\n } else if (!clientState.authenticationInfo) {\n return await forceRefreshToken(false);\n } else if (currentTimeSecs + AUTH_TOKEN_REFRESH_BEFORE_EXPIRATION_SECONDS > clientState.authenticationInfo.expiresAtSeconds) {\n // Small edge case: If we were being proactive\n // and the auth information hasn't expired yet, swallow any exceptions\n const returnCached = currentTimeSecs < clientState.authenticationInfo.expiresAtSeconds;\n return await forceRefreshToken(returnCached);\n } else {\n return clientState.authenticationInfo;\n }\n },\n async getAccessTokenForOrg(orgId) {\n // First, check if there is a valid access token for the org ID in the\n // valid time frame.\n const currentTimeSecs = currentTimeSeconds();\n const activeOrgAccessToken = clientState.accessTokenActiveOrgMap[orgId];\n if (!!activeOrgAccessToken) {\n if (currentTimeSecs < activeOrgAccessToken.fetchedAt + ACTIVE_ORG_ACCESS_TOKEN_REFRESH_EXPIRATION_SECONDS) {\n return {\n accessToken: activeOrgAccessToken.accessToken,\n error: undefined\n };\n }\n }\n // Fetch the access token for the org ID and update.\n try {\n const authenticationInfo = await runWithRetriesOnAnyError(() => fetchAuthenticationInfo(clientState.authUrl, orgId));\n if (!authenticationInfo) {\n // Only null if 401 unauthorized.\n return {\n error: \"user_not_in_org\",\n accessToken: null\n };\n }\n const {\n accessToken\n } = authenticationInfo;\n clientState.accessTokenActiveOrgMap[orgId] = {\n accessToken,\n fetchedAt: currentTimeSecs\n };\n return {\n accessToken,\n error: undefined\n };\n } catch (e) {\n return {\n error: \"unexpected_error\",\n accessToken: null\n };\n }\n },\n getSignupPageUrl(options) {\n return getSignupPageUrl(options);\n },\n getLoginPageUrl(options) {\n return getLoginPageUrl(options);\n },\n getAccountPageUrl(options) {\n return getAccountPageUrl(options);\n },\n getOrgPageUrl(orgId, options) {\n return getOrgPageUrl(orgId, options);\n },\n getCreateOrgPageUrl(options) {\n return getCreateOrgPageUrl(options);\n },\n getSetupSAMLPageUrl(orgId, options) {\n return getSetupSAMLPageUrl(orgId, options);\n },\n redirectToSignupPage(options) {\n window.location.href = getSignupPageUrl(options);\n },\n redirectToLoginPage(options) {\n window.location.href = getLoginPageUrl(options);\n },\n redirectToAccountPage(options) {\n window.location.href = getAccountPageUrl(options);\n },\n redirectToOrgPage(orgId, options) {\n window.location.href = getOrgPageUrl(orgId, options);\n },\n redirectToCreateOrgPage(options) {\n window.location.href = getCreateOrgPageUrl(options);\n },\n redirectToSetupSAMLPage(orgId, options) {\n window.location.href = getSetupSAMLPageUrl(orgId, options);\n },\n async logout(redirectAfterLogout) {\n const logoutResponse = await logout(clientState.authUrl);\n setAuthenticationInfoAndUpdateDownstream(null);\n if (redirectAfterLogout) {\n window.location.href = logoutResponse.redirect_to;\n }\n },\n destroy() {\n clientState.observers = [];\n clientState.accessTokenObservers = [];\n window.removeEventListener(\"storage\", onStorageChange);\n if (clientState.refreshInterval) {\n clearInterval(clientState.refreshInterval);\n }\n }\n };\n const onStorageChange = async function () {\n // If localStorage isn't available, nothing to do here.\n // This usually happens in frameworks that have some SSR components\n if (!hasLocalStorage()) {\n return;\n }\n const loggedOutAt = getLocalStorageNumber(LOGGED_OUT_AT_KEY);\n const loggedInAt = getLocalStorageNumber(LOGGED_IN_AT_KEY);\n\n // If we've detected a logout event after the last one our client is aware of, trigger a refresh\n if (loggedOutAt && (!clientState.lastLoggedOutAtMessage || loggedOutAt > clientState.lastLoggedOutAtMessage)) {\n clientState.lastLoggedOutAtMessage = loggedOutAt;\n if (clientState.authenticationInfo) {\n await forceRefreshToken(true);\n }\n }\n\n // If we've detected a login event after the last one our client is aware of, trigger a refresh\n if (loggedInAt && (!clientState.lastLoggedInAtMessage || loggedInAt > clientState.lastLoggedInAtMessage)) {\n clientState.lastLoggedInAtMessage = loggedInAt;\n if (!clientState.authenticationInfo) {\n await forceRefreshToken(true);\n }\n }\n };\n\n // If we were offline or on a different tab, when we return, refetch auth info\n // Some browsers trigger focus more often than we'd like, so we'll debounce a little here as well\n const onOnlineOrFocus = async function () {\n if (clientState.lastRefresh && currentTimeSeconds() > clientState.lastRefresh + DEBOUNCE_DURATION_FOR_REFOCUS_SECONDS) {\n await forceRefreshToken(true);\n } else {\n await client.getAuthenticationInfoOrNull();\n }\n };\n if (hasWindow()) {\n window.addEventListener(\"storage\", onStorageChange);\n window.addEventListener(\"online\", onOnlineOrFocus);\n window.addEventListener(\"focus\", onOnlineOrFocus);\n if (authOptions.enableBackgroundTokenRefresh) {\n client.getAuthenticationInfoOrNull();\n clientState.refreshInterval = window.setInterval(client.getAuthenticationInfoOrNull, 60000);\n }\n }\n return client;\n}\n\nexport { ACTIVE_ORG_ID_COOKIE_NAME, OrgMemberInfoClass, UserClass, createClient, getActiveOrgId, setActiveOrgId };\n//# sourceMappingURL=index.js.map\n","import { useContext } from \"react\"\nimport { AuthContext } from \"../AuthContext\"\n\nconst DEPRECATED_ORG_SELECTION_LOCAL_STORAGE_KEY = \"__last_selected_org\"\n\n/**\n * @deprecated This hook is deprecated and no longer supported.\n */\nexport function useActiveOrg() {\n const context = useContext(AuthContext)\n if (context === undefined) {\n throw new Error(\"useActiveOrg must be used within an AuthProvider or RequiredAuthProvider\")\n }\n\n if (context.loading || !context.authInfo || !context.authInfo.orgHelper) {\n return null\n }\n\n const proposedActiveOrgIdOrName = context.activeOrgFn()\n if (!proposedActiveOrgIdOrName) {\n return null\n }\n\n const orgHelper = context.authInfo.orgHelper\n return orgHelper.getOrg(proposedActiveOrgIdOrName) || orgHelper.getOrgByName(proposedActiveOrgIdOrName)\n}\n\nexport function saveOrgSelectionToLocalStorage(orgIdOrName: string) {\n if (localStorage) {\n localStorage.setItem(DEPRECATED_ORG_SELECTION_LOCAL_STORAGE_KEY, orgIdOrName)\n }\n}\n\nexport function loadOrgSelectionFromLocalStorage(): string | null {\n if (localStorage) {\n return localStorage.getItem(DEPRECATED_ORG_SELECTION_LOCAL_STORAGE_KEY)\n }\n return null\n}\n","import { createClient, IAuthClient } from \"@propelauth/javascript\"\nimport { MutableRefObject, useCallback, useEffect, useRef, useState } from \"react\"\n\ntype ClientRef = {\n authUrl: string\n client: IAuthClient\n}\n\nexport const useClientRef = (props: { authUrl: string }) => {\n const [accessTokenChangeCounter, setAccessTokenChangeCounter] = useState(0)\n const { authUrl } = props\n\n // Use a ref to store the client so that it doesn't get recreated on every render\n const clientRef = useRef(null)\n if (clientRef.current === null) {\n const client = createClient({ authUrl, enableBackgroundTokenRefresh: true })\n client.addAccessTokenChangeObserver(() => setAccessTokenChangeCounter((x) => x + 1))\n clientRef.current = { authUrl, client }\n }\n\n // If the authUrl changes, destroy the old client and create a new one\n useEffect(() => {\n if (clientRef.current === null) {\n return\n } else if (clientRef.current.authUrl === authUrl) {\n return\n } else {\n clientRef.current.client.destroy()\n\n const newClient = createClient({ authUrl, enableBackgroundTokenRefresh: true })\n newClient.addAccessTokenChangeObserver(() => setAccessTokenChangeCounter((x) => x + 1))\n clientRef.current = { authUrl, client: newClient }\n }\n }, [authUrl])\n\n return { clientRef, accessTokenChangeCounter }\n}\n\nexport const useClientRefCallback = (\n clientRef: MutableRefObject,\n callback: (client: IAuthClient) => (...inputs: I) => O\n): ((...inputs: I) => O) => {\n return useCallback(\n (...inputs: I) => {\n const client = clientRef.current?.client\n if (!client) {\n throw new Error(\"Client is not initialized\")\n }\n return callback(client)(...inputs)\n },\n [callback]\n )\n}\n","import {\n AccessTokenForActiveOrg,\n AuthenticationInfo,\n RedirectToAccountOptions,\n RedirectToCreateOrgOptions,\n RedirectToLoginOptions,\n RedirectToOrgPageOptions,\n RedirectToSetupSAMLPageOptions,\n RedirectToSignupOptions,\n} from \"@propelauth/javascript\"\nimport React, { useCallback, useEffect, useReducer } from \"react\"\nimport { loadOrgSelectionFromLocalStorage } from \"./hooks/useActiveOrg\"\nimport { useClientRef, useClientRefCallback } from \"./useClientRef\"\n\nexport interface Tokens {\n getAccessTokenForOrg: (orgId: string) => Promise\n}\n\nexport interface InternalAuthState {\n loading: boolean\n authInfo: AuthenticationInfo | null\n\n logout: (redirectOnLogout: boolean) => Promise\n activeOrgFn: () => string | null\n\n redirectToLoginPage: (options?: RedirectToLoginOptions) => void\n redirectToSignupPage: (options?: RedirectToSignupOptions) => void\n redirectToAccountPage: (options?: RedirectToAccountOptions) => void\n redirectToOrgPage: (orgId?: string, options?: RedirectToOrgPageOptions) => void\n redirectToCreateOrgPage: (options?: RedirectToCreateOrgOptions) => void\n redirectToSetupSAMLPage: (orgId: string, options?: RedirectToSetupSAMLPageOptions) => void\n\n getSignupPageUrl(options?: RedirectToSignupOptions): string\n getLoginPageUrl(options?: RedirectToLoginOptions): string\n getAccountPageUrl(options?: RedirectToAccountOptions): string\n getOrgPageUrl(orgId?: string, options?: RedirectToOrgPageOptions): string\n getCreateOrgPageUrl(options?: RedirectToCreateOrgOptions): string\n getSetupSAMLPageUrl(orgId: string, options?: RedirectToSetupSAMLPageOptions): string\n tokens: Tokens\n refreshAuthInfo: () => Promise\n defaultDisplayWhileLoading?: React.ReactElement\n defaultDisplayIfLoggedOut?: React.ReactElement\n}\n\nexport type AuthProviderProps = {\n authUrl: string\n defaultDisplayWhileLoading?: React.ReactElement\n defaultDisplayIfLoggedOut?: React.ReactElement\n /**\n * getActiveOrgFn is deprecated. Use `useActiveOrgV2` instead.\n */\n getActiveOrgFn?: () => string | null\n children?: React.ReactNode\n}\n\nexport interface RequiredAuthProviderProps\n extends Omit {\n displayWhileLoading?: React.ReactElement\n displayIfLoggedOut?: React.ReactElement\n}\n\nexport const AuthContext = React.createContext(undefined)\n\ntype AuthInfoState = {\n loading: boolean\n authInfo: AuthenticationInfo | null\n}\n\nconst initialAuthInfoState: AuthInfoState = {\n loading: true,\n authInfo: null,\n}\n\ntype AuthInfoStateAction = {\n authInfo: AuthenticationInfo | null\n}\n\nfunction authInfoStateReducer(_state: AuthInfoState, action: AuthInfoStateAction): AuthInfoState {\n if (!action.authInfo) {\n return {\n loading: false,\n authInfo: action.authInfo,\n }\n } else if (_state.loading) {\n return {\n loading: false,\n authInfo: action.authInfo,\n }\n } else if (_state.authInfo && _state.authInfo.accessToken !== action.authInfo.accessToken) {\n return {\n loading: false,\n authInfo: action.authInfo,\n }\n } else {\n return _state\n }\n}\n\nexport const AuthProvider = (props: AuthProviderProps) => {\n const [authInfoState, dispatch] = useReducer(authInfoStateReducer, initialAuthInfoState)\n const { clientRef, accessTokenChangeCounter } = useClientRef({ authUrl: props.authUrl })\n\n // Refresh the token when the user has logged in or out\n useEffect(() => {\n let didCancel = false\n\n async function refreshToken() {\n const client = clientRef.current?.client\n if (!client) {\n return\n }\n\n try {\n const authInfo = await client.getAuthenticationInfoOrNull()\n if (!didCancel) {\n dispatch({ authInfo })\n }\n } catch (_) {\n // Important errors are logged in the client library\n }\n }\n\n refreshToken()\n return () => {\n didCancel = true\n }\n }, [accessTokenChangeCounter])\n\n // Deprecation warning\n useEffect(() => {\n if (props.getActiveOrgFn) {\n console.warn(\"The `getActiveOrgFn` prop is deprecated.\")\n }\n }, [])\n\n const logout = useClientRefCallback(clientRef, (client) => client.logout)\n const redirectToLoginPage = useClientRefCallback(clientRef, (client) => client.redirectToLoginPage)\n const redirectToSignupPage = useClientRefCallback(clientRef, (client) => client.redirectToSignupPage)\n const redirectToAccountPage = useClientRefCallback(clientRef, (client) => client.redirectToAccountPage)\n const redirectToOrgPage = useClientRefCallback(clientRef, (client) => client.redirectToOrgPage)\n const redirectToCreateOrgPage = useClientRefCallback(clientRef, (client) => client.redirectToCreateOrgPage)\n const redirectToSetupSAMLPage = useClientRefCallback(clientRef, (client) => client.redirectToSetupSAMLPage)\n\n const getLoginPageUrl = useClientRefCallback(clientRef, (client) => client.getLoginPageUrl)\n const getSignupPageUrl = useClientRefCallback(clientRef, (client) => client.getSignupPageUrl)\n const getAccountPageUrl = useClientRefCallback(clientRef, (client) => client.getAccountPageUrl)\n const getOrgPageUrl = useClientRefCallback(clientRef, (client) => client.getOrgPageUrl)\n const getCreateOrgPageUrl = useClientRefCallback(clientRef, (client) => client.getCreateOrgPageUrl)\n const getSetupSAMLPageUrl = useClientRefCallback(clientRef, (client) => client.getSetupSAMLPageUrl)\n\n const getAccessTokenForOrg = useClientRefCallback(clientRef, (client) => client.getAccessTokenForOrg)\n\n const refreshAuthInfo = useCallback(async () => {\n if (clientRef.current === null) {\n return\n }\n\n const client = clientRef.current.client\n const authInfo = await client.getAuthenticationInfoOrNull(true)\n dispatch({ authInfo })\n }, [dispatch])\n\n // TODO: Remove this, as both `getActiveOrgFn` and `loadOrgSelectionFromLocalStorage` are deprecated.\n const deprecatedActiveOrgFn = props.getActiveOrgFn || loadOrgSelectionFromLocalStorage\n\n const { defaultDisplayWhileLoading, defaultDisplayIfLoggedOut } = props\n const value: InternalAuthState = {\n loading: authInfoState.loading,\n authInfo: authInfoState.authInfo,\n logout,\n defaultDisplayWhileLoading,\n defaultDisplayIfLoggedOut,\n redirectToLoginPage,\n redirectToSignupPage,\n redirectToAccountPage,\n redirectToOrgPage,\n redirectToCreateOrgPage,\n redirectToSetupSAMLPage,\n getLoginPageUrl,\n activeOrgFn: deprecatedActiveOrgFn,\n getSignupPageUrl,\n getAccountPageUrl,\n getOrgPageUrl,\n getCreateOrgPageUrl,\n getSetupSAMLPageUrl,\n refreshAuthInfo,\n tokens: {\n getAccessTokenForOrg,\n },\n }\n return {props.children}\n}\n","import { AccessHelper, OrgHelper, User, UserClass } from \"@propelauth/javascript\"\nimport { useContext } from \"react\"\nimport { AuthContext, Tokens } from \"../AuthContext\"\n\nexport type UseAuthInfoLoading = {\n loading: true\n isLoggedIn: undefined\n accessToken: undefined\n user: undefined\n userClass: undefined\n orgHelper: undefined\n accessHelper: undefined\n isImpersonating: undefined\n impersonatorUserId: undefined\n refreshAuthInfo: () => Promise\n tokens: Tokens\n accessTokenExpiresAtSeconds: undefined\n}\n\nexport type UseAuthInfoLoggedInProps = {\n loading: false\n isLoggedIn: true\n accessToken: string\n user: User\n userClass: UserClass\n orgHelper: OrgHelper\n accessHelper: AccessHelper\n isImpersonating: boolean\n impersonatorUserId?: string\n refreshAuthInfo: () => Promise\n tokens: Tokens\n accessTokenExpiresAtSeconds: number\n}\n\nexport type UseAuthInfoNotLoggedInProps = {\n loading: false\n isLoggedIn: false\n accessToken: null\n user: null\n userClass: null\n orgHelper: null\n accessHelper: null\n isImpersonating: false\n impersonatorUserId: undefined\n refreshAuthInfo: () => Promise\n tokens: Tokens\n accessTokenExpiresAtSeconds: undefined\n}\n\nexport type UseAuthInfoProps = UseAuthInfoLoading | UseAuthInfoLoggedInProps | UseAuthInfoNotLoggedInProps\n\nexport function useAuthInfo(): UseAuthInfoProps {\n const context = useContext(AuthContext)\n if (context === undefined) {\n throw new Error(\"useAuthInfo must be used within an AuthProvider or RequiredAuthProvider\")\n }\n\n const { loading, authInfo, refreshAuthInfo, tokens } = context\n if (loading) {\n return {\n loading: true,\n isLoggedIn: undefined,\n accessToken: undefined,\n orgHelper: undefined,\n accessHelper: undefined,\n user: undefined,\n userClass: undefined,\n isImpersonating: undefined,\n impersonatorUserId: undefined,\n refreshAuthInfo,\n tokens,\n accessTokenExpiresAtSeconds: undefined,\n }\n } else if (authInfo && authInfo.accessToken) {\n return {\n loading: false,\n isLoggedIn: true,\n accessToken: authInfo.accessToken,\n orgHelper: authInfo.orgHelper,\n accessHelper: authInfo.accessHelper,\n user: authInfo.user,\n userClass: authInfo.userClass,\n isImpersonating: !!authInfo.impersonatorUserId,\n impersonatorUserId: authInfo.impersonatorUserId,\n refreshAuthInfo,\n tokens,\n accessTokenExpiresAtSeconds: authInfo.expiresAtSeconds,\n }\n }\n return {\n loading: false,\n isLoggedIn: false,\n accessToken: null,\n user: null,\n userClass: null,\n orgHelper: null,\n accessHelper: null,\n isImpersonating: false,\n impersonatorUserId: undefined,\n refreshAuthInfo,\n tokens,\n accessTokenExpiresAtSeconds: undefined,\n }\n}\n","import React, { useContext, useEffect } from \"react\"\nimport { AuthContext } from \"../AuthContext\"\n\nexport function useRedirectFunctions() {\n const context = useContext(AuthContext)\n if (context === undefined) {\n throw new Error(\"useRedirectFunctions must be used within an AuthProvider or RequiredAuthProvider\")\n }\n const {\n redirectToAccountPage,\n redirectToSignupPage,\n redirectToLoginPage,\n redirectToOrgPage,\n redirectToCreateOrgPage,\n redirectToSetupSAMLPage,\n } = context\n return {\n redirectToSignupPage,\n redirectToLoginPage,\n redirectToAccountPage,\n redirectToOrgPage,\n redirectToCreateOrgPage,\n redirectToSetupSAMLPage,\n }\n}\n\nexport interface RedirectProps {\n children?: React.ReactNode\n}\n\nexport interface RedirectToSignupProps extends RedirectProps {\n postSignupRedirectUrl?: string\n userSignupQueryParameters?: Record\n}\n\nexport function RedirectToSignup({\n children,\n postSignupRedirectUrl,\n userSignupQueryParameters,\n}: RedirectToSignupProps) {\n const { redirectToSignupPage } = useRedirectFunctions()\n\n useEffect(() => redirectToSignupPage({ postSignupRedirectUrl, userSignupQueryParameters }), [])\n\n return <>{children}\n}\n\nexport interface RedirectToLoginProps extends RedirectProps {\n postLoginRedirectUrl?: string\n}\n\nexport function RedirectToLogin({ children, postLoginRedirectUrl }: RedirectToLoginProps) {\n const { redirectToLoginPage } = useRedirectFunctions()\n useEffect(() => {\n if (postLoginRedirectUrl) {\n redirectToLoginPage({ postLoginRedirectUrl })\n } else {\n redirectToLoginPage()\n }\n }, [])\n return <>{children}\n}\n","/** @license React v16.13.1\n * react-is.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'use strict';var b=\"function\"===typeof Symbol&&Symbol.for,c=b?Symbol.for(\"react.element\"):60103,d=b?Symbol.for(\"react.portal\"):60106,e=b?Symbol.for(\"react.fragment\"):60107,f=b?Symbol.for(\"react.strict_mode\"):60108,g=b?Symbol.for(\"react.profiler\"):60114,h=b?Symbol.for(\"react.provider\"):60109,k=b?Symbol.for(\"react.context\"):60110,l=b?Symbol.for(\"react.async_mode\"):60111,m=b?Symbol.for(\"react.concurrent_mode\"):60111,n=b?Symbol.for(\"react.forward_ref\"):60112,p=b?Symbol.for(\"react.suspense\"):60113,q=b?\nSymbol.for(\"react.suspense_list\"):60120,r=b?Symbol.for(\"react.memo\"):60115,t=b?Symbol.for(\"react.lazy\"):60116,v=b?Symbol.for(\"react.block\"):60121,w=b?Symbol.for(\"react.fundamental\"):60117,x=b?Symbol.for(\"react.responder\"):60118,y=b?Symbol.for(\"react.scope\"):60119;\nfunction z(a){if(\"object\"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;\nexports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};\nexports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};\nexports.isValidElementType=function(a){return\"string\"===typeof a||\"function\"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||\"object\"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;\n","/** @license React v16.13.1\n * react-is.development.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'use strict';\n\n\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n'use strict';\n\n// The Symbol used to tag the ReactElement-like types. If there is no native Symbol\n// nor polyfill, then a plain number is used for performance.\nvar hasSymbol = typeof Symbol === 'function' && Symbol.for;\nvar REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;\nvar REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;\nvar REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;\nvar REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;\nvar REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;\nvar REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;\nvar REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary\n// (unstable) APIs that have been removed. Can we remove the symbols?\n\nvar REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;\nvar REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;\nvar REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;\nvar REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;\nvar REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;\nvar REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;\nvar REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;\nvar REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;\nvar REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;\nvar REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;\nvar REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;\n\nfunction isValidElementType(type) {\n return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.\n type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);\n}\n\nfunction typeOf(object) {\n if (typeof object === 'object' && object !== null) {\n var $$typeof = object.$$typeof;\n\n switch ($$typeof) {\n case REACT_ELEMENT_TYPE:\n var type = object.type;\n\n switch (type) {\n case REACT_ASYNC_MODE_TYPE:\n case REACT_CONCURRENT_MODE_TYPE:\n case REACT_FRAGMENT_TYPE:\n case REACT_PROFILER_TYPE:\n case REACT_STRICT_MODE_TYPE:\n case REACT_SUSPENSE_TYPE:\n return type;\n\n default:\n var $$typeofType = type && type.$$typeof;\n\n switch ($$typeofType) {\n case REACT_CONTEXT_TYPE:\n case REACT_FORWARD_REF_TYPE:\n case REACT_LAZY_TYPE:\n case REACT_MEMO_TYPE:\n case REACT_PROVIDER_TYPE:\n return $$typeofType;\n\n default:\n return $$typeof;\n }\n\n }\n\n case REACT_PORTAL_TYPE:\n return $$typeof;\n }\n }\n\n return undefined;\n} // AsyncMode is deprecated along with isAsyncMode\n\nvar AsyncMode = REACT_ASYNC_MODE_TYPE;\nvar ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;\nvar ContextConsumer = REACT_CONTEXT_TYPE;\nvar ContextProvider = REACT_PROVIDER_TYPE;\nvar Element = REACT_ELEMENT_TYPE;\nvar ForwardRef = REACT_FORWARD_REF_TYPE;\nvar Fragment = REACT_FRAGMENT_TYPE;\nvar Lazy = REACT_LAZY_TYPE;\nvar Memo = REACT_MEMO_TYPE;\nvar Portal = REACT_PORTAL_TYPE;\nvar Profiler = REACT_PROFILER_TYPE;\nvar StrictMode = REACT_STRICT_MODE_TYPE;\nvar Suspense = REACT_SUSPENSE_TYPE;\nvar hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated\n\nfunction isAsyncMode(object) {\n {\n if (!hasWarnedAboutDeprecatedIsAsyncMode) {\n hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint\n\n console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');\n }\n }\n\n return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;\n}\nfunction isConcurrentMode(object) {\n return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;\n}\nfunction isContextConsumer(object) {\n return typeOf(object) === REACT_CONTEXT_TYPE;\n}\nfunction isContextProvider(object) {\n return typeOf(object) === REACT_PROVIDER_TYPE;\n}\nfunction isElement(object) {\n return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n}\nfunction isForwardRef(object) {\n return typeOf(object) === REACT_FORWARD_REF_TYPE;\n}\nfunction isFragment(object) {\n return typeOf(object) === REACT_FRAGMENT_TYPE;\n}\nfunction isLazy(object) {\n return typeOf(object) === REACT_LAZY_TYPE;\n}\nfunction isMemo(object) {\n return typeOf(object) === REACT_MEMO_TYPE;\n}\nfunction isPortal(object) {\n return typeOf(object) === REACT_PORTAL_TYPE;\n}\nfunction isProfiler(object) {\n return typeOf(object) === REACT_PROFILER_TYPE;\n}\nfunction isStrictMode(object) {\n return typeOf(object) === REACT_STRICT_MODE_TYPE;\n}\nfunction isSuspense(object) {\n return typeOf(object) === REACT_SUSPENSE_TYPE;\n}\n\nexports.AsyncMode = AsyncMode;\nexports.ConcurrentMode = ConcurrentMode;\nexports.ContextConsumer = ContextConsumer;\nexports.ContextProvider = ContextProvider;\nexports.Element = Element;\nexports.ForwardRef = ForwardRef;\nexports.Fragment = Fragment;\nexports.Lazy = Lazy;\nexports.Memo = Memo;\nexports.Portal = Portal;\nexports.Profiler = Profiler;\nexports.StrictMode = StrictMode;\nexports.Suspense = Suspense;\nexports.isAsyncMode = isAsyncMode;\nexports.isConcurrentMode = isConcurrentMode;\nexports.isContextConsumer = isContextConsumer;\nexports.isContextProvider = isContextProvider;\nexports.isElement = isElement;\nexports.isForwardRef = isForwardRef;\nexports.isFragment = isFragment;\nexports.isLazy = isLazy;\nexports.isMemo = isMemo;\nexports.isPortal = isPortal;\nexports.isProfiler = isProfiler;\nexports.isStrictMode = isStrictMode;\nexports.isSuspense = isSuspense;\nexports.isValidElementType = isValidElementType;\nexports.typeOf = typeOf;\n })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-is.production.min.js');\n} else {\n module.exports = require('./cjs/react-is.development.js');\n}\n","'use strict';\n\nvar reactIs = require('react-is');\n\n/**\n * Copyright 2015, Yahoo! Inc.\n * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.\n */\nvar REACT_STATICS = {\n childContextTypes: true,\n contextType: true,\n contextTypes: true,\n defaultProps: true,\n displayName: true,\n getDefaultProps: true,\n getDerivedStateFromError: true,\n getDerivedStateFromProps: true,\n mixins: true,\n propTypes: true,\n type: true\n};\nvar KNOWN_STATICS = {\n name: true,\n length: true,\n prototype: true,\n caller: true,\n callee: true,\n arguments: true,\n arity: true\n};\nvar FORWARD_REF_STATICS = {\n '$$typeof': true,\n render: true,\n defaultProps: true,\n displayName: true,\n propTypes: true\n};\nvar MEMO_STATICS = {\n '$$typeof': true,\n compare: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n type: true\n};\nvar TYPE_STATICS = {};\nTYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;\nTYPE_STATICS[reactIs.Memo] = MEMO_STATICS;\n\nfunction getStatics(component) {\n // React v16.11 and below\n if (reactIs.isMemo(component)) {\n return MEMO_STATICS;\n } // React v16.12 and above\n\n\n return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;\n}\n\nvar defineProperty = Object.defineProperty;\nvar getOwnPropertyNames = Object.getOwnPropertyNames;\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar getPrototypeOf = Object.getPrototypeOf;\nvar objectPrototype = Object.prototype;\nfunction hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {\n if (typeof sourceComponent !== 'string') {\n // don't hoist over string (html) components\n if (objectPrototype) {\n var inheritedComponent = getPrototypeOf(sourceComponent);\n\n if (inheritedComponent && inheritedComponent !== objectPrototype) {\n hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);\n }\n }\n\n var keys = getOwnPropertyNames(sourceComponent);\n\n if (getOwnPropertySymbols) {\n keys = keys.concat(getOwnPropertySymbols(sourceComponent));\n }\n\n var targetStatics = getStatics(targetComponent);\n var sourceStatics = getStatics(sourceComponent);\n\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n\n if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {\n var descriptor = getOwnPropertyDescriptor(sourceComponent, key);\n\n try {\n // Avoid failures from read-only properties\n defineProperty(targetComponent, key, descriptor);\n } catch (e) {}\n }\n }\n }\n\n return targetComponent;\n}\n\nmodule.exports = hoistNonReactStatics;\n","import React from \"react\"\nimport { AuthProvider, RequiredAuthProviderProps } from \"./AuthContext\"\nimport { WithLoggedInAuthInfoProps } from \"./withAuthInfo\"\nimport { withRequiredAuthInfo } from \"./withRequiredAuthInfo\"\n\nconst RequiredAuthWrappedComponent = withRequiredAuthInfo(\n ({ children }: { children: React.ReactNode } & WithLoggedInAuthInfoProps) => <>{children}\n)\n\nexport const RequiredAuthProvider = (props: RequiredAuthProviderProps) => {\n const { children, displayIfLoggedOut, displayWhileLoading, ...sharedProps } = props\n\n return (\n \n {children}\n \n )\n}\n","import hoistNonReactStatics from \"hoist-non-react-statics\"\nimport React, { useContext } from \"react\"\nimport { Subtract } from \"utility-types\"\nimport { AuthContext } from \"./AuthContext\"\nimport { RedirectToLogin } from \"./hooks/useRedirectFunctions\"\nimport { WithLoggedInAuthInfoProps } from \"./withAuthInfo\"\n\nexport interface WithRequiredAuthInfoArgs {\n displayWhileLoading?: React.ReactElement\n displayIfLoggedOut?: React.ReactElement\n}\n\nexport function withRequiredAuthInfo

(\n Component: React.ComponentType

,\n args?: WithRequiredAuthInfoArgs\n): React.ComponentType> {\n const displayName = `withRequiredAuthInfo(${Component.displayName || Component.name || \"Component\"})`\n\n const WithRequiredAuthInfoWrapper = (props: Subtract) => {\n const context = useContext(AuthContext)\n if (context === undefined) {\n throw new Error(\"withRequiredAuthInfo must be used within an AuthProvider or RequiredAuthProvider\")\n }\n\n const { loading, authInfo, defaultDisplayIfLoggedOut, defaultDisplayWhileLoading, refreshAuthInfo, tokens } =\n context\n\n function displayLoading() {\n if (args?.displayWhileLoading) {\n return args.displayWhileLoading\n } else if (defaultDisplayWhileLoading) {\n return defaultDisplayWhileLoading\n }\n return \n }\n\n function displayLoggedOut() {\n if (args?.displayIfLoggedOut) {\n return args.displayIfLoggedOut\n } else if (defaultDisplayIfLoggedOut) {\n return defaultDisplayIfLoggedOut\n }\n return \n }\n\n if (loading) {\n return displayLoading()\n } else if (authInfo) {\n const loggedInProps: P = {\n ...(props as P),\n accessToken: authInfo.accessToken,\n isLoggedIn: !!authInfo.accessToken,\n orgHelper: authInfo.orgHelper,\n accessHelper: authInfo.accessHelper,\n user: authInfo.user,\n userClass: authInfo.userClass,\n isImpersonating: !!authInfo.impersonatorUserId,\n impersonatorUserId: authInfo.impersonatorUserId,\n refreshAuthInfo,\n tokens,\n accessTokenExpiresAtSeconds: authInfo.expiresAtSeconds,\n }\n return \n } else {\n return displayLoggedOut()\n }\n }\n WithRequiredAuthInfoWrapper.displayName = displayName\n WithRequiredAuthInfoWrapper.WrappedComponent = Component\n\n return hoistNonReactStatics(WithRequiredAuthInfoWrapper, Component)\n}\n","////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n /**\n * The last action that modified the current location. This will always be\n * Action.Pop when a history instance is first created. This value is mutable.\n */\n readonly action: Action;\n\n /**\n * The current location. This value is mutable.\n */\n readonly location: Location;\n\n /**\n * Returns a valid href for the given `to` value that may be used as\n * the value of an attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\n\n /**\n * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route () since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly {\n let location: Readonly = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n };\n return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial) {\n if (search && search !== \"?\")\n pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\")\n pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial {\n let parsedPath: Partial = {};\n\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n window?: Window;\n v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n createHref: (window: Window, to: To) => string,\n validateLocation: ((location: Location, to: To) => void) | null,\n options: UrlHistoryOptions = {}\n): UrlHistory {\n let { window = document.defaultView!, v5Compat = false } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n // Treating this as a full URL will strip any trailing spaces so we need to\n // pre-encode them since they might be part of a matching splat param from\n // an ancestor route\n href = href.replace(/ $/, \"%20\");\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: unknown;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n // We keep the raw Response for redirects so we can return it verbatim\n response: Response;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: unknown;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface HandlerResult {\n type: \"data\" | \"error\";\n result: unknown; // data, Error, Response, DeferredData\n status?: number;\n}\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `

`,\n * useSubmit(), ``, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable | null;\n\ntype DataFunctionReturnValue = Promise | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction = {\n (\n args: LoaderFunctionArgs,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (\n args: ActionFunctionArgs,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n unstable_actionStatus?: number;\n actionResult?: any;\n defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n extends AgnosticRouteMatch {\n shouldLoad: boolean;\n resolve: (\n handlerOverride?: (\n handler: (ctx?: unknown) => DataFunctionReturnValue\n ) => Promise\n ) => Promise;\n}\n\nexport interface DataStrategyFunctionArgs\n extends DataFunctionArgs {\n matches: DataStrategyMatch[];\n}\n\nexport interface DataStrategyFunction {\n (args: DataStrategyFunctionArgs): Promise;\n}\n\nexport interface AgnosticPatchRoutesOnMissFunction<\n M extends AgnosticRouteMatch = AgnosticRouteMatch\n> {\n (opts: {\n path: string;\n matches: M[];\n patch: (routeId: string | null, children: AgnosticRouteObject[]) => void;\n }): void | Promise;\n}\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction {\n (): Promise>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n caseSensitive?: boolean;\n path?: string;\n id?: string;\n loader?: LoaderFunction | boolean;\n action?: ActionFunction | boolean;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\n lazy?: LazyRouteFunction;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam | _PathParam\n : // find params after `:`\n Path extends `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam =\n // check if path is just a wildcard\n Path extends \"*\" | \"/*\"\n ? \"*\"\n : // look for wildcard at the end of the path\n Path extends `${infer Rest}/*`\n ? \"*\" | _PathParam\n : // look for params in the absence of wildcards\n _PathParam;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey =\n // if you could not find path params, fallback to `string`\n [PathParam] extends [never] ? string : PathParam;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params = {\n readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The route object that was used to match.\n */\n route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n extends AgnosticRouteMatch {}\n\nfunction isIndexRoute(\n route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n routes: AgnosticRouteObject[],\n mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: string[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, String(index)];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(\n route.index !== true || !route.children,\n `Cannot specify children on an index route`\n );\n invariant(\n !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename = \"/\"\n): AgnosticRouteMatch[] | null {\n return matchRoutesImpl(routes, locationArg, basename, false);\n}\n\nexport function matchRoutesImpl<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename: string,\n allowPartial: boolean\n): AgnosticRouteMatch[] | null {\n let location =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n let pathname = stripBasename(location.pathname || \"/\", basename);\n\n if (pathname == null) {\n return null;\n }\n\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n\n let matches = null;\n for (let i = 0; matches == null && i < branches.length; ++i) {\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n let decoded = decodePath(pathname);\n matches = matchRouteBranch(\n branches[i],\n decoded,\n allowPartial\n );\n }\n\n return matches;\n}\n\nexport interface UIMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch,\n pathname: string,\n allowPartial = false\n): AgnosticRouteMatch[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch[] = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname =\n matchedPathname === \"/\"\n ? pathname\n : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath(\n { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n remainingPathname\n );\n\n let route = meta.route;\n\n if (\n !match &&\n end &&\n allowPartial &&\n !routesMeta[routesMeta.length - 1].route.index\n ) {\n match = matchPath(\n {\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end: false,\n },\n remainingPathname\n );\n }\n\n if (!match) {\n return null;\n }\n\n Object.assign(matchedParams, match.params);\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(\n joinPaths([matchedPathname, match.pathnameBase])\n ),\n route,\n });\n\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n\n return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern {\n /**\n * A string to match against a URL pathname. May contain `:id`-style segments\n * to indicate placeholders for dynamic parameters. May also end with `/*` to\n * indicate matching the rest of the URL pathname.\n */\n path: Path;\n /**\n * Should be `true` if the static portions of the `path` should be matched in\n * the same case.\n */\n caseSensitive?: boolean;\n /**\n * Should be `true` if this pattern should match the entire URL pathname.\n */\n end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The pattern that was used to match.\n */\n pattern: PathPattern;\n}\n\ntype Mutable = {\n -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey,\n Path extends string\n>(\n pattern: PathPattern | Path,\n pathname: string\n): PathMatch | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, compiledParams] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = compiledParams.reduce>(\n (memo, { paramName, isOptional }, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n }\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, CompiledPathParam[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let params: CompiledPathParam[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(\n /\\/:([\\w-]+)(\\?)?/g,\n (_: string, paramName: string, isOptional) => {\n params.push({ paramName, isOptional: isOptional != null });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n }\n );\n\n if (path.endsWith(\"*\")) {\n params.push({ paramName: \"*\" });\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, params];\n}\n\nfunction decodePath(value: string) {\n try {\n return value\n .split(\"/\")\n .map((v) => decodeURIComponent(v).replace(/\\//g, \"%2F\"))\n .join(\"/\");\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n pathname: string,\n basename: string\n): string | null {\n if (basename === \"/\") return pathname;\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\")\n ? basename.length - 1\n : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n\n return pathname.slice(startIndex) || \"/\";\n}\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\",\n } = typeof to === \"string\" ? parsePath(to) : to;\n\n let pathname = toPathname\n ? toPathname.startsWith(\"/\")\n ? toPathname\n : resolvePathname(toPathname, fromPathname)\n : fromPathname;\n\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash),\n };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n\n relativeSegments.forEach((segment) => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n char: string,\n field: string,\n dest: string,\n path: Partial\n) {\n return (\n `Cannot include a '${char}' character in a manually specified ` +\n `\\`to.${field}\\` field [${JSON.stringify(\n path\n )}]. Please separate it out to the ` +\n `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n `a string in and the router will parse it for you.`\n );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = { ...toArg };\n\n invariant(\n !to.pathname || !to.pathname.includes(\"?\"),\n getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n );\n invariant(\n !to.pathname || !to.pathname.includes(\"#\"),\n getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n );\n invariant(\n !to.search || !to.search.includes(\"#\"),\n getInvalidPathError(\"#\", \"search\", \"hash\", to)\n );\n }\n\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n let from: string;\n\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n !search || search === \"?\"\n ? \"\"\n : search.startsWith(\"?\")\n ? search\n : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = (\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n\n return new Response(JSON.stringify(data), {\n ...responseInit,\n headers,\n });\n};\n\nexport interface TrackedPromise extends Promise {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n DataStrategyMatch,\n AgnosticRouteObject,\n DataResult,\n DataStrategyFunction,\n DataStrategyFunctionArgs,\n DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n HandlerResult,\n ImmutableRouteKey,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\n AgnosticPatchRoutesOnMissFunction,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n getResolveToMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n matchRoutesImpl,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(key: string): Fetcher;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete the fetcher for a given key\n * @param key\n */\n deleteFetcher(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE DO NOT USE\n *\n * Patch additional children routes into an existing parent route\n * @param routeId The parent route id or a callback function accepting `patch`\n * to perform batch patching\n * @param children The additional children routes\n */\n patchRoutes(routeId: string | null, children: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map;\n}\n\n/**\n * State maintained internally by the router. During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\n\n /**\n * The current location reflected by the router\n */\n location: Location;\n\n /**\n * The current set of route matches\n */\n matches: AgnosticDataRouteMatch[];\n\n /**\n * Tracks whether we've completed our initial data load\n */\n initialized: boolean;\n\n /**\n * Current scroll position we should start at for a new view\n * - number -> scroll position to restore to\n * - false -> do not restore scroll at all (used during submissions)\n * - null -> don't have a saved position, scroll to hash or top of page\n */\n restoreScrollPosition: number | false | null;\n\n /**\n * Indicate whether this navigation should skip resetting the scroll position\n * if we are unable to restore the scroll position\n */\n preventScrollReset: boolean;\n\n /**\n * Tracks the state of the current navigation\n */\n navigation: Navigation;\n\n /**\n * Tracks any in-progress revalidations\n */\n revalidation: RevalidationState;\n\n /**\n * Data from the loaders for the current matches\n */\n loaderData: RouteData;\n\n /**\n * Data from the action for the current matches\n */\n actionData: RouteData | null;\n\n /**\n * Errors caught from loaders for the current matches\n */\n errors: RouteData | null;\n\n /**\n * Map of current fetchers\n */\n fetchers: Map;\n\n /**\n * Map of current blockers\n */\n blockers: Map;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n unstable_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n unstable_patchRoutesOnMiss?: AgnosticPatchRoutesOnMissFunction;\n unstable_dataStrategy?: DataStrategyFunction;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record;\n actionHeaders: Record;\n activeDeferreds: Record | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n unstable_dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: {\n routeId?: string;\n requestContext?: unknown;\n unstable_dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n deletedFetchers: string[];\n unstable_viewTransitionOpts?: ViewTransitionOpts;\n unstable_flushSync: boolean;\n }\n ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n unstable_viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher =\n FetcherStates[keyof FetcherStates];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\ntype PendingActionResult = [string, SuccessResult | ErrorResult];\n\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Route matches which may have been updated from fog of war discovery\n */\n matches?: RouterState[\"matches\"];\n /**\n * Tuple for the returned or thrown value from the current action. The routeId\n * is the action route for success and the bubbled boundary route for errors.\n */\n pendingActionResult?: PendingActionResult;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n /**\n * Route matches which may have been updated from fog of war discovery\n */\n matches?: RouterState[\"matches\"];\n /**\n * loaderData returned from the current set of loaders\n */\n loaderData?: RouterState[\"loaderData\"];\n /**\n * errors thrown from the current set of loaders\n */\n errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n let dataStrategyImpl = init.unstable_dataStrategy || defaultDataStrategy;\n let patchRoutesOnMissImpl = init.unstable_patchRoutesOnMiss;\n\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n unstable_skipActionErrorRevalidation: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record | null = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition: GetScrollPositionFunction | null = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null && !patchRoutesOnMissImpl) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n // If the user provided a patchRoutesOnMiss implementation and our initial\n // match is a splat route, clear them out so we run through lazy discovery\n // on hydration in case there's a more accurate lazy route match\n if (initialMatches && patchRoutesOnMissImpl) {\n let fogOfWar = checkFogOfWar(\n initialMatches,\n dataRoutes,\n init.history.location.pathname\n );\n if (fogOfWar.active) {\n initialMatches = null;\n }\n }\n\n let initialized: boolean;\n if (!initialMatches) {\n // We need to run patchRoutesOnMiss in initialize()\n initialized = false;\n initialMatches = [];\n } else if (initialMatches.some((m) => m.route.lazy)) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!initialMatches.some((m) => m.route.loader)) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n let isRouteInitialized = (m: AgnosticDataRouteMatch) => {\n // No loader, nothing to initialize\n if (!m.route.loader) {\n return true;\n }\n // Explicitly opting-in to running on hydration\n if (\n typeof m.route.loader === \"function\" &&\n m.route.loader.hydrate === true\n ) {\n return false;\n }\n // Otherwise, initialized if hydrated with data or an error\n return (\n (loaderData && loaderData[m.route.id] !== undefined) ||\n (errors && errors[m.route.id] !== undefined)\n );\n };\n\n // If errors exist, don't consider routes below the boundary\n if (errors) {\n let idx = initialMatches.findIndex(\n (m) => errors![m.route.id] !== undefined\n );\n initialized = initialMatches.slice(0, idx + 1).every(isRouteInitialized);\n } else {\n initialized = initialMatches.every(isRouteInitialized);\n }\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map> = new Map<\n string,\n Set\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n\n // Map of pending patchRoutesOnMiss() promises (keyed by path/matches) so\n // that we only kick them off once for a given combo\n let pendingPatchRoutes = new Map<\n string,\n ReturnType\n >();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let ignoreNextHistoryUpdate = false;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n ignoreNextHistoryUpdate = true;\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked\n init.history.go(delta);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location, {\n initialHydration: true,\n });\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(\n newState: Partial,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach((subscriber) =>\n subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n unstable_viewTransitionOpts: opts.viewTransitionOpts,\n unstable_flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n }\n }\n\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(\n location: Location,\n newState: Partial>,\n { flushSync }: { flushSync?: boolean } = {}\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === HistoryAction.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n {\n viewTransitionOpts,\n flushSync: flushSync === true,\n }\n );\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\n }\n\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(\n to: number | To | null,\n opts?: RouterNavigateOptions\n ): Promise {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.unstable_viewTransition,\n flushSync,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n { overrideNavigation: state.navigation }\n );\n }\n\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(\n historyAction: HistoryAction,\n location: Location,\n opts?: {\n initialHydration?: boolean;\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: boolean;\n flushSync?: boolean;\n }\n ): Promise {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n\n let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let { error, notFoundMatches, route } = handleNavigational404(\n location.pathname\n );\n completeNavigation(\n location,\n {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n },\n { flushSync }\n );\n return;\n }\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial load will always\n // be \"same hash\". For example, on /page#hash and submit a \n // which will default to a navigation to /page\n if (\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches }, { flushSync });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionResult: PendingActionResult | undefined;\n\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingActionResult = [\n findNearestBoundary(matches).route.id,\n { type: ResultType.error, error: opts.pendingError },\n ];\n } else if (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\n // Call action if we received an action submission\n let actionResult = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n fogOfWar.active,\n { replace: opts.replace, flushSync }\n );\n\n if (actionResult.shortCircuited) {\n return;\n }\n\n // If we received a 404 from handleAction, it's because we couldn't lazily\n // discover the destination route so we don't want to call loaders\n if (actionResult.pendingActionResult) {\n let [routeId, result] = actionResult.pendingActionResult;\n if (\n isErrorResult(result) &&\n isRouteErrorResponse(result.error) &&\n result.error.status === 404\n ) {\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches: actionResult.matches,\n loaderData: {},\n errors: {\n [routeId]: result.error,\n },\n });\n return;\n }\n }\n\n matches = actionResult.matches || matches;\n pendingActionResult = actionResult.pendingActionResult;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n // No need to do fog of war matching again on loader execution\n fogOfWar.active = false;\n\n // Create a GET request for the loaders\n request = createClientSideRequest(\n init.history,\n request.url,\n request.signal\n );\n }\n\n // Call loaders\n let {\n shortCircuited,\n matches: updatedMatches,\n loaderData,\n errors,\n } = await handleLoaders(\n request,\n location,\n matches,\n fogOfWar.active,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.fetcherSubmission,\n opts && opts.replace,\n opts && opts.initialHydration === true,\n flushSync,\n pendingActionResult\n );\n\n if (shortCircuited) {\n return;\n }\n\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches: updatedMatches || matches,\n ...getActionDataForCommit(pendingActionResult),\n loaderData,\n errors,\n });\n }\n\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(\n request: Request,\n location: Location,\n submission: Submission,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n opts: { replace?: boolean; flushSync?: boolean } = {}\n ): Promise {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n matches,\n location.pathname,\n request.signal\n );\n if (discoverResult.type === \"aborted\") {\n return { shortCircuited: true };\n } else if (discoverResult.type === \"error\") {\n let { error, notFoundMatches, route } = handleDiscoverRouteError(\n location.pathname,\n discoverResult\n );\n return {\n matches: notFoundMatches,\n pendingActionResult: [\n route.id,\n {\n type: ResultType.error,\n error,\n },\n ],\n };\n } else if (!discoverResult.matches) {\n let { notFoundMatches, error, route } = handleNavigational404(\n location.pathname\n );\n return {\n matches: notFoundMatches,\n pendingActionResult: [\n route.id,\n {\n type: ResultType.error,\n error,\n },\n ],\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n let results = await callDataStrategy(\n \"action\",\n request,\n [actionMatch],\n matches\n );\n result = results[0];\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n let location = normalizeRedirectLocation(\n result.response.headers.get(\"Location\")!,\n new URL(request.url),\n basename\n );\n replace = location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(request, result, {\n submission,\n replace,\n });\n return { shortCircuited: true };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n // By default, all submissions to the current location are REPLACE\n // navigations, but if the action threw an error that'll be rendered in\n // an errorElement, we fall back to PUSH so that the user can use the\n // back button to get back to the pre-submission form location to try\n // again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n matches,\n pendingActionResult: [boundaryMatch.route.id, result],\n };\n }\n\n return {\n matches,\n pendingActionResult: [actionMatch.route.id, result],\n };\n }\n\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: boolean,\n pendingActionResult?: PendingActionResult\n ): Promise {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n // If we have partialHydration enabled, then don't update the state for the\n // initial data load since it's not a \"navigation\"\n let shouldUpdateNavigationState =\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration);\n\n // When fog of war is enabled, we enter our `loading` state earlier so we\n // can discover new routes during the `loading` state. We skip this if\n // we've already run actions since we would have done our matching already.\n // If the children() function threw then, we want to proceed with the\n // partial matches it discovered.\n if (isFogOfWar) {\n if (shouldUpdateNavigationState) {\n let actionData = getUpdatedActionData(pendingActionResult);\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData !== undefined ? { actionData } : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n let discoverResult = await discoverRoutes(\n matches,\n location.pathname,\n request.signal\n );\n\n if (discoverResult.type === \"aborted\") {\n return { shortCircuited: true };\n } else if (discoverResult.type === \"error\") {\n let { error, notFoundMatches, route } = handleDiscoverRouteError(\n location.pathname,\n discoverResult\n );\n return {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n };\n } else if (!discoverResult.matches) {\n let { error, notFoundMatches, route } = handleNavigational404(\n location.pathname\n );\n return {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n future.unstable_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionResult\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(\n location,\n {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors:\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? { [pendingActionResult[0]]: pendingActionResult[1].error }\n : null,\n ...getActionDataForCommit(pendingActionResult),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n },\n { flushSync }\n );\n return { shortCircuited: true };\n }\n\n if (shouldUpdateNavigationState) {\n let updates: Partial = {};\n if (!isFogOfWar) {\n // Only update navigation/actionNData if we didn't already do it above\n updates.navigation = loadingNavigation;\n let actionData = getUpdatedActionData(pendingActionResult);\n if (actionData !== undefined) {\n updates.actionData = actionData;\n }\n }\n if (revalidatingFetchers.length > 0) {\n updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n }\n updateState(updates, { flushSync });\n }\n\n revalidatingFetchers.forEach((rf) => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect([...loaderResults, ...fetcherResults]);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(request, redirect.result, {\n replace,\n });\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n matchesToLoad,\n loaderResults,\n pendingActionResult,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n // During partial hydration, preserve SSR errors for routes that don't re-run\n if (future.v7_partialHydration && initialHydration && state.errors) {\n Object.entries(state.errors)\n .filter(([id]) => !matchesToLoad.some((m) => m.route.id === id))\n .forEach(([routeId, error]) => {\n errors = Object.assign(errors || {}, { [routeId]: error });\n });\n }\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n matches,\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n function getUpdatedActionData(\n pendingActionResult: PendingActionResult | undefined\n ): Record | null | undefined {\n if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n // This is cast to `any` currently because `RouteData`uses any and it\n // would be a breaking change to use any.\n // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n return {\n [pendingActionResult[0]]: pendingActionResult[1].data as any,\n };\n } else if (state.actionData) {\n if (Object.keys(state.actionData).length === 0) {\n return null;\n } else {\n return state.actionData;\n }\n }\n }\n\n function getUpdatedRevalidatingFetchers(\n revalidatingFetchers: RevalidatingFetcher[]\n ) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n return new Map(state.fetchers);\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath }),\n { flushSync }\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n fogOfWar.active,\n flushSync,\n submission\n );\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n fogOfWar.active,\n flushSync,\n submission\n );\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n flushSync: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n function detectAndHandle405Error(m: AgnosticDataRouteMatch) {\n if (!m.route.action && !m.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error, { flushSync });\n return true;\n }\n return false;\n }\n\n if (!isFogOfWar && detectAndHandle405Error(match)) {\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync,\n });\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n requestMatches,\n path,\n fetchRequest.signal\n );\n\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n let { error } = handleDiscoverRouteError(path, discoverResult);\n setFetcherError(key, routeId, error, { flushSync });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: path }),\n { flushSync }\n );\n return;\n } else {\n requestMatches = discoverResult.matches;\n match = getTargetMatch(requestMatches, path);\n\n if (detectAndHandle405Error(match)) {\n return;\n }\n }\n }\n\n // Call the action for the fetcher\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResults = await callDataStrategy(\n \"action\",\n fetchRequest,\n [match],\n requestMatches\n );\n let actionResult = actionResults[0];\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(fetchRequest, actionResult, {\n fetcherSubmission: submission,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n false,\n future.unstable_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n [match.route.id, actionResult]\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect([...loaderResults, ...fetcherResults]);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(revalidationRequest, redirect.result);\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n state.matches,\n matchesToLoad,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n fetchers: new Map(state.fetchers),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n flushSync: boolean,\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(\n key,\n getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n ),\n { flushSync }\n );\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n matches,\n path,\n fetchRequest.signal\n );\n\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n let { error } = handleDiscoverRouteError(path, discoverResult);\n setFetcherError(key, routeId, error, { flushSync });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: path }),\n { flushSync }\n );\n return;\n } else {\n matches = discoverResult.matches;\n match = getTargetMatch(matches, path);\n }\n }\n\n // Call the loader for this fetcher route match\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let results = await callDataStrategy(\n \"loader\",\n fetchRequest,\n [match],\n matches\n );\n let result = results[0];\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(fetchRequest, result);\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n request: Request,\n redirect: RedirectResult,\n {\n submission,\n fetcherSubmission,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n isRevalidationRequired = true;\n }\n\n let location = redirect.response.headers.get(\"Location\");\n invariant(location, \"Expected a Location header on the redirect Response\");\n location = normalizeRedirectLocation(\n location,\n new URL(request.url),\n basename\n );\n let redirectLocation = createLocation(state.location, location, {\n _isRedirect: true,\n });\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(location)) {\n const url = init.history.createURL(location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(location);\n } else {\n routerWindow.location.assign(location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.response.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n }\n }\n\n // Utility wrapper for calling dataStrategy client-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(\n type: \"loader\" | \"action\",\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[]\n ): Promise {\n try {\n let results = await callDataStrategyImpl(\n dataStrategyImpl,\n type,\n request,\n matchesToLoad,\n matches,\n manifest,\n mapRouteProperties\n );\n\n return await Promise.all(\n results.map((result, i) => {\n if (isRedirectHandlerResult(result)) {\n let response = result.result as Response;\n return {\n type: ResultType.redirect,\n response: normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n matchesToLoad[i].route.id,\n matches,\n basename,\n future.v7_relativeSplatPath\n ),\n };\n }\n\n return convertHandlerResultToDataResult(result);\n })\n );\n } catch (e) {\n // If the outer dataStrategy method throws, just return the error for all\n // matches - and it'll naturally bubble to the root\n return matchesToLoad.map(() => ({\n type: ResultType.error,\n error: e,\n }));\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n let [loaderResults, ...fetcherResults] = await Promise.all([\n matchesToLoad.length\n ? callDataStrategy(\"loader\", request, matchesToLoad, matches)\n : [],\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n let fetcherRequest = createClientSideRequest(\n init.history,\n f.path,\n f.controller.signal\n );\n return callDataStrategy(\n \"loader\",\n fetcherRequest,\n [f.match],\n f.matches\n ).then((r) => r[0]);\n } else {\n return Promise.resolve({\n type: ResultType.error,\n error: getInternalRouterError(404, {\n pathname: f.path,\n }),\n });\n }\n }),\n ]);\n\n await Promise.all([\n resolveDeferredResults(\n currentMatches,\n matchesToLoad,\n loaderResults,\n loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\n true\n ),\n ]);\n\n return {\n loaderResults,\n fetcherResults,\n };\n }\n\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.push(key);\n abortFetcher(key);\n }\n });\n }\n\n function updateFetcherState(\n key: string,\n fetcher: Fetcher,\n opts: { flushSync?: boolean } = {}\n ) {\n state.fetchers.set(key, fetcher);\n updateState(\n { fetchers: new Map(state.fetchers) },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function setFetcherError(\n key: string,\n routeId: string,\n error: any,\n opts: { flushSync?: boolean } = {}\n ) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState(\n {\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function getFetcher(key: string): Fetcher {\n if (future.v7_fetcherPersist) {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n deletedFetchers.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n if (future.v7_fetcherPersist) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n } else {\n activeFetchers.set(key, count);\n }\n } else {\n deleteFetcher(key);\n }\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n invariant(controller, `Expected fetch controller: ${key}`);\n controller.abort();\n fetchControllers.delete(key);\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function handleNavigational404(pathname: string) {\n let error = getInternalRouterError(404, { pathname });\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let { matches, route } = getShortCircuitMatches(routesToUse);\n\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n\n return { notFoundMatches: matches, route, error };\n }\n\n function handleDiscoverRouteError(\n pathname: string,\n discoverResult: DiscoverRoutesErrorResult\n ) {\n let matches = discoverResult.partialMatches;\n let route = matches[matches.length - 1].route;\n let error = getInternalRouterError(400, {\n type: \"route-discovery\",\n routeId: route.id,\n pathname,\n message:\n discoverResult.error != null && \"message\" in discoverResult.error\n ? discoverResult.error\n : String(discoverResult.error),\n });\n return { notFoundMatches: matches, route, error };\n }\n\n function cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the component\n function enableScrollRestoration(\n positions: Record,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || null;\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered \n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({ restoreScrollPosition: y });\n }\n }\n\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n\n function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function checkFogOfWar(\n matches: AgnosticDataRouteMatch[] | null,\n routesToUse: AgnosticDataRouteObject[],\n pathname: string\n ): { active: boolean; matches: AgnosticDataRouteMatch[] | null } {\n if (patchRoutesOnMissImpl) {\n if (!matches) {\n let fogMatches = matchRoutesImpl(\n routesToUse,\n pathname,\n basename,\n true\n );\n\n return { active: true, matches: fogMatches || [] };\n } else {\n let leafRoute = matches[matches.length - 1].route;\n if (\n leafRoute.path &&\n (leafRoute.path === \"*\" || leafRoute.path.endsWith(\"/*\"))\n ) {\n // If we matched a splat, it might only be because we haven't yet fetched\n // the children that would match with a higher score, so let's fetch\n // around and find out\n let partialMatches = matchRoutesImpl(\n routesToUse,\n pathname,\n basename,\n true\n );\n return { active: true, matches: partialMatches };\n }\n }\n }\n\n return { active: false, matches: null };\n }\n\n type DiscoverRoutesSuccessResult = {\n type: \"success\";\n matches: AgnosticDataRouteMatch[] | null;\n };\n type DiscoverRoutesErrorResult = {\n type: \"error\";\n error: any;\n partialMatches: AgnosticDataRouteMatch[];\n };\n type DiscoverRoutesAbortedResult = { type: \"aborted\" };\n type DiscoverRoutesResult =\n | DiscoverRoutesSuccessResult\n | DiscoverRoutesErrorResult\n | DiscoverRoutesAbortedResult;\n\n async function discoverRoutes(\n matches: AgnosticDataRouteMatch[],\n pathname: string,\n signal: AbortSignal\n ): Promise {\n let partialMatches: AgnosticDataRouteMatch[] | null = matches;\n let route =\n partialMatches.length > 0\n ? partialMatches[partialMatches.length - 1].route\n : null;\n while (true) {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n try {\n await loadLazyRouteChildren(\n patchRoutesOnMissImpl!,\n pathname,\n partialMatches,\n routesToUse,\n manifest,\n mapRouteProperties,\n pendingPatchRoutes,\n signal\n );\n } catch (e) {\n return { type: \"error\", error: e, partialMatches };\n } finally {\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity so when we `updateState` at the end of\n // this navigation/fetch `router.routes` will be a new identity and\n // trigger a re-run of memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR) {\n dataRoutes = [...dataRoutes];\n }\n }\n\n if (signal.aborted) {\n return { type: \"aborted\" };\n }\n\n let newMatches = matchRoutes(routesToUse, pathname, basename);\n let matchedSplat = false;\n if (newMatches) {\n let leafRoute = newMatches[newMatches.length - 1].route;\n\n if (leafRoute.index) {\n // If we found an index route, we can stop\n return { type: \"success\", matches: newMatches };\n }\n\n if (leafRoute.path && leafRoute.path.length > 0) {\n if (leafRoute.path === \"*\") {\n // If we found a splat route, we can't be sure there's not a\n // higher-scoring route down some partial matches trail so we need\n // to check that out\n matchedSplat = true;\n } else {\n // If we found a non-splat route, we can stop\n return { type: \"success\", matches: newMatches };\n }\n }\n }\n\n let newPartialMatches = matchRoutesImpl(\n routesToUse,\n pathname,\n basename,\n true\n );\n\n // If we are no longer partially matching anything, this was either a\n // legit splat match above, or it's a 404. Also avoid loops if the\n // second pass results in the same partial matches\n if (\n !newPartialMatches ||\n partialMatches.map((m) => m.route.id).join(\"-\") ===\n newPartialMatches.map((m) => m.route.id).join(\"-\")\n ) {\n return { type: \"success\", matches: matchedSplat ? newMatches : null };\n }\n\n partialMatches = newPartialMatches;\n route = partialMatches[partialMatches.length - 1].route;\n if (route.path === \"*\") {\n // The splat is still our most accurate partial, so run with it\n return { type: \"success\", matches: partialMatches };\n }\n }\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n function patchRoutes(\n routeId: string | null,\n children: AgnosticRouteObject[]\n ): void {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n patchRoutesImpl(\n routeId,\n children,\n routesToUse,\n manifest,\n mapRouteProperties\n );\n\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity and trigger a reflow via `updateState`\n // to re-run memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR) {\n dataRoutes = [...dataRoutes];\n updateState({});\n }\n }\n\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n patchRoutes,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n v7_throwAbortReason: false,\n ...(opts ? opts.future : null),\n };\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n *\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n * the bubbling of errors which allows single-fetch-type implementations\n * where the client will handle the bubbling and we may need to return data\n * for the handling route\n */\n async function query(\n request: Request,\n {\n requestContext,\n skipLoaderErrorBubbling,\n unstable_dataStrategy,\n }: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n unstable_dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n unstable_dataStrategy || null,\n skipLoaderErrorBubbling === true,\n null\n );\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n *\n * - `opts.routeId` allows you to specify the specific route handler to call.\n * If not provided the handler will determine the proper route by matching\n * against `request.url`\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n unstable_dataStrategy,\n }: {\n requestContext?: unknown;\n routeId?: string;\n unstable_dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n unstable_dataStrategy || null,\n false,\n match\n );\n\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n unstable_dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n unstable_dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n unstable_dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction for a\n // `queryRoute` call, we throw the `HandlerResult` to bail out early\n // and then return or throw the raw Response here accordingly\n if (isHandlerResult(e) && isResponse(e.result)) {\n if (e.type === ResultType.error) {\n throw e.result;\n }\n return e.result;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n unstable_dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n isRouteRequest: boolean\n ): Promise | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n let results = await callDataStrategy(\n \"action\",\n request,\n [actionMatch],\n matches,\n isRouteRequest,\n requestContext,\n unstable_dataStrategy\n );\n result = results[0];\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.response.status,\n headers: {\n Location: result.response.headers.get(\"Location\")!,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = skipLoaderErrorBubbling\n ? actionMatch\n : findNearestBoundary(matches, actionMatch.route.id);\n\n let context = await loadRouteData(\n loaderRequest,\n matches,\n requestContext,\n unstable_dataStrategy,\n skipLoaderErrorBubbling,\n null,\n [boundaryMatch.route.id, result]\n );\n\n // action status codes take precedence over loader status codes\n return {\n ...context,\n statusCode: isRouteErrorResponse(result.error)\n ? result.error.status\n : result.statusCode != null\n ? result.statusCode\n : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n let context = await loadRouteData(\n loaderRequest,\n matches,\n requestContext,\n unstable_dataStrategy,\n skipLoaderErrorBubbling,\n null\n );\n\n return {\n ...context,\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionHeaders: result.headers\n ? { [actionMatch.route.id]: result.headers }\n : {},\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n unstable_dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null,\n pendingActionResult?: PendingActionResult\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : pendingActionResult && isErrorResult(pendingActionResult[1])\n ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0])\n : matches;\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors:\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? {\n [pendingActionResult[0]]: pendingActionResult[1].error,\n }\n : null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await callDataStrategy(\n \"loader\",\n request,\n matchesToLoad,\n matches,\n isRouteRequest,\n requestContext,\n unstable_dataStrategy\n );\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionResult,\n activeDeferreds,\n skipLoaderErrorBubbling\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n // Utility wrapper for calling dataStrategy server-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(\n type: \"loader\" | \"action\",\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n isRouteRequest: boolean,\n requestContext: unknown,\n unstable_dataStrategy: DataStrategyFunction | null\n ): Promise {\n let results = await callDataStrategyImpl(\n unstable_dataStrategy || defaultDataStrategy,\n type,\n request,\n matchesToLoad,\n matches,\n manifest,\n mapRouteProperties,\n requestContext\n );\n\n return await Promise.all(\n results.map((result, i) => {\n if (isRedirectHandlerResult(result)) {\n let response = result.result as Response;\n // Throw redirects and let the server handle them with an HTTP redirect\n throw normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n matchesToLoad[i].route.id,\n matches,\n basename,\n future.v7_relativeSplatPath\n );\n }\n if (isResponse(result.result) && isRouteRequest) {\n // For SSR single-route requests, we want to hand Responses back\n // directly without unwrapping\n throw result;\n }\n\n return convertHandlerResultToDataResult(result);\n })\n );\n }\n\n return {\n dataRoutes,\n query,\n queryRoute,\n };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n routes: AgnosticDataRouteObject[],\n context: StaticHandlerContext,\n error: any\n) {\n let newContext: StaticHandlerContext = {\n ...context,\n statusCode: isRouteErrorResponse(error) ? error.status : 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\n}\n\nfunction throwStaticHandlerAbortedError(\n request: Request,\n isRouteRequest: boolean,\n future: StaticHandlerFutureConfig\n) {\n if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\n}\n\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n matches: AgnosticDataRouteMatch[],\n boundaryId: string\n) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isInitialLoad: boolean,\n skipActionErrorRevalidation: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n deletedFetchers: Set,\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionResult?: PendingActionResult\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingActionResult\n ? isErrorResult(pendingActionResult[1])\n ? pendingActionResult[1].error\n : pendingActionResult[1].data\n : undefined;\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryId =\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? pendingActionResult[0]\n : undefined;\n let boundaryMatches = boundaryId\n ? getLoaderMatchesUntilBoundary(matches, boundaryId)\n : matches;\n\n // Don't revalidate loaders by default after action 4xx/5xx responses\n // when the flag is enabled. They can still opt-into revalidation via\n // `shouldRevalidate` via `actionResult`\n let actionStatus = pendingActionResult\n ? pendingActionResult[1].statusCode\n : undefined;\n let shouldSkipRevalidation =\n skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let { route } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n\n if (route.loader == null) {\n return false;\n }\n\n if (isInitialLoad) {\n if (typeof route.loader !== \"function\" || route.loader.hydrate) {\n return true;\n }\n return (\n state.loaderData[route.id] === undefined &&\n // Don't re-run if the loader ran and threw an error\n (!state.errors || state.errors[route.id] === undefined)\n );\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n unstable_actionStatus: actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation\n ? false\n : // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial load (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (\n isInitialLoad ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.has(key)\n ) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.includes(key)) {\n // Always revalidate if the fetcher was cancelled\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n unstable_actionStatus: actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation\n ? false\n : isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\n/**\n * Idempotent utility to execute patchRoutesOnMiss() to lazily load route\n * definitions and update the routes/routeManifest\n */\nasync function loadLazyRouteChildren(\n patchRoutesOnMissImpl: AgnosticPatchRoutesOnMissFunction,\n path: string,\n matches: AgnosticDataRouteMatch[],\n routes: AgnosticDataRouteObject[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n pendingRouteChildren: Map>,\n signal: AbortSignal\n) {\n let key = [path, ...matches.map((m) => m.route.id)].join(\"-\");\n try {\n let pending = pendingRouteChildren.get(key);\n if (!pending) {\n pending = patchRoutesOnMissImpl({\n path,\n matches,\n patch: (routeId, children) => {\n if (!signal.aborted) {\n patchRoutesImpl(\n routeId,\n children,\n routes,\n manifest,\n mapRouteProperties\n );\n }\n },\n });\n pendingRouteChildren.set(key, pending);\n }\n\n if (pending && isPromise(pending)) {\n await pending;\n }\n } finally {\n pendingRouteChildren.delete(key);\n }\n}\n\nfunction patchRoutesImpl(\n routeId: string | null,\n children: AgnosticRouteObject[],\n routesToUse: AgnosticDataRouteObject[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction\n) {\n if (routeId) {\n let route = manifest[routeId];\n invariant(\n route,\n `No route found to patch children into: routeId = ${routeId}`\n );\n let dataChildren = convertRoutesToDataRoutes(\n children,\n mapRouteProperties,\n [routeId, \"patch\", String(route.children?.length || \"0\")],\n manifest\n );\n if (route.children) {\n route.children.push(...dataChildren);\n } else {\n route.children = dataChildren;\n }\n } else {\n let dataChildren = convertRoutesToDataRoutes(\n children,\n mapRouteProperties,\n [\"patch\", String(routesToUse.length || \"0\")],\n manifest\n );\n routesToUse.push(...dataChildren);\n }\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nfunction defaultDataStrategy(\n opts: DataStrategyFunctionArgs\n): ReturnType {\n return Promise.all(opts.matches.map((m) => m.resolve()));\n}\n\nasync function callDataStrategyImpl(\n dataStrategyImpl: DataStrategyFunction,\n type: \"loader\" | \"action\",\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n requestContext?: unknown\n): Promise {\n let routeIdsToLoad = matchesToLoad.reduce(\n (acc, m) => acc.add(m.route.id),\n new Set()\n );\n let loadedMatches = new Set();\n\n // Send all matches here to allow for a middleware-type implementation.\n // handler will be a no-op for unneeded routes and we filter those results\n // back out below.\n let results = await dataStrategyImpl({\n matches: matches.map((match) => {\n let shouldLoad = routeIdsToLoad.has(match.route.id);\n // `resolve` encapsulates the route.lazy, executing the\n // loader/action, and mapping return values/thrown errors to a\n // HandlerResult. Users can pass a callback to take fine-grained control\n // over the execution of the loader/action\n let resolve: DataStrategyMatch[\"resolve\"] = (handlerOverride) => {\n loadedMatches.add(match.route.id);\n return shouldLoad\n ? callLoaderOrAction(\n type,\n request,\n match,\n manifest,\n mapRouteProperties,\n handlerOverride,\n requestContext\n )\n : Promise.resolve({ type: ResultType.data, result: undefined });\n };\n\n return {\n ...match,\n shouldLoad,\n resolve,\n };\n }),\n request,\n params: matches[0].params,\n context: requestContext,\n });\n\n // Throw if any loadRoute implementations not called since they are what\n // ensures a route is fully loaded\n matches.forEach((m) =>\n invariant(\n loadedMatches.has(m.route.id),\n `\\`match.resolve()\\` was not called for route id \"${m.route.id}\". ` +\n \"You must call `match.resolve()` on every match passed to \" +\n \"`dataStrategy` to ensure all routes are properly loaded.\"\n )\n );\n\n // Filter out any middleware-only matches for which we didn't need to run handlers\n return results.filter((_, i) => routeIdsToLoad.has(matches[i].route.id));\n}\n\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n handlerOverride: Parameters[0],\n staticContext?: unknown\n): Promise {\n let result: HandlerResult;\n let onReject: (() => void) | undefined;\n\n let runHandler = (\n handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n ): Promise => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n // This will never resolve so safe to type it as Promise to\n // satisfy the function return value\n let abortPromise = new Promise((_, r) => (reject = r));\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n\n let actualHandler = (ctx?: unknown) => {\n if (typeof handler !== \"function\") {\n return Promise.reject(\n new Error(\n `You cannot call the handler for a route which defines a boolean ` +\n `\"${type}\" [routeId: ${match.route.id}]`\n )\n );\n }\n return handler(\n {\n request,\n params: match.params,\n context: staticContext,\n },\n ...(ctx !== undefined ? [ctx] : [])\n );\n };\n\n let handlerPromise: Promise;\n if (handlerOverride) {\n handlerPromise = handlerOverride((ctx: unknown) => actualHandler(ctx));\n } else {\n handlerPromise = (async () => {\n try {\n let val = await actualHandler();\n return { type: \"data\", result: val };\n } catch (e) {\n return { type: \"error\", result: e };\n }\n })();\n }\n\n return Promise.race([handlerPromise, abortPromise]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let [value] = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadLazyRouteModule(match.route, mapRouteProperties, manifest),\n ]);\n if (handlerError !== undefined) {\n throw handlerError;\n }\n result = value!;\n } else {\n // Load lazy route module, then run any returned handler\n await loadLazyRouteModule(match.route, mapRouteProperties, manifest);\n\n handler = match.route[type];\n if (handler) {\n // Handler still runs even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, result: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result.result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n // We should already be catching and converting normal handler executions to\n // HandlerResults and returning them, so anything that throws here is an\n // unexpected error we still need to wrap\n return { type: ResultType.error, result: e };\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n return result;\n}\n\nasync function convertHandlerResultToDataResult(\n handlerResult: HandlerResult\n): Promise {\n let { result, type, status } = handlerResult;\n\n if (isResponse(result)) {\n let data: any;\n\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return { type: ResultType.error, error: e };\n }\n\n if (type === ResultType.error) {\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(result.status, result.statusText, data),\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n if (type === ResultType.error) {\n return {\n type: ResultType.error,\n error: result,\n statusCode: isRouteErrorResponse(result) ? result.status : status,\n };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result, statusCode: status };\n}\n\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(\n response: Response,\n request: Request,\n routeId: string,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n v7_relativeSplatPath: boolean\n) {\n let location = response.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n let trimmedMatches = matches.slice(\n 0,\n matches.findIndex((m) => m.route.id === routeId) + 1\n );\n location = normalizeTo(\n new URL(request.url),\n trimmedMatches,\n basename,\n true,\n location,\n v7_relativeSplatPath\n );\n response.headers.set(\"Location\", location);\n }\n\n return response;\n}\n\nfunction normalizeRedirectLocation(\n location: string,\n currentUrl: URL,\n basename: string\n): string {\n if (ABSOLUTE_URL_REGEX.test(location)) {\n // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n let normalizedLocation = location;\n let url = normalizedLocation.startsWith(\"//\")\n ? new URL(currentUrl.protocol + normalizedLocation)\n : new URL(normalizedLocation);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n return url.pathname + url.search + url.hash;\n }\n }\n return location;\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingActionResult: PendingActionResult | undefined,\n activeDeferreds: Map,\n skipLoaderErrorBubbling: boolean\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record;\n} {\n // Fill in loaderData/errors from our loaders\n let loaderData: RouterState[\"loaderData\"] = {};\n let errors: RouterState[\"errors\"] | null = null;\n let statusCode: number | undefined;\n let foundError = false;\n let loaderHeaders: Record = {};\n let pendingError =\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? pendingActionResult[1].error\n : undefined;\n\n // Process loader results into state.loaderData/state.errors\n results.forEach((result, index) => {\n let id = matchesToLoad[index].route.id;\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError !== undefined) {\n error = pendingError;\n pendingError = undefined;\n }\n\n errors = errors || {};\n\n if (skipLoaderErrorBubbling) {\n errors[id] = error;\n } else {\n // Look upwards from the matched route for the closest ancestor error\n // boundary, defaulting to the root match. Prefer higher error values\n // if lower errors bubble to the same boundary\n let boundaryMatch = findNearestBoundary(matches, id);\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n loaderData[id] = result.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (result.statusCode && result.statusCode !== 200 && !foundError) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError !== undefined && pendingActionResult) {\n errors = { [pendingActionResult[0]]: pendingError };\n loaderData[pendingActionResult[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingActionResult: PendingActionResult | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: DataResult[],\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionResult,\n activeDeferreds,\n false // This method is only called client side so we always want to bubble\n );\n\n // Process results from our revalidating fetchers\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, match, controller } = revalidatingFetchers[index];\n invariant(\n fetcherResults !== undefined && fetcherResults[index] !== undefined,\n \"Did not find corresponding fetcher result\"\n );\n let result = fetcherResults[index];\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\nfunction getActionDataForCommit(\n pendingActionResult: PendingActionResult | undefined\n) {\n if (!pendingActionResult) {\n return {};\n }\n return isErrorResult(pendingActionResult[1])\n ? {\n // Clear out prior actionData on errors\n actionData: {},\n }\n : {\n actionData: {\n [pendingActionResult[0]]: pendingActionResult[1].data,\n },\n };\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n message,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\" | \"route-discovery\";\n message?: string;\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (type === \"route-discovery\") {\n errorMessage =\n `Unable to match URL \"${pathname}\" - the \\`children()\\` function for ` +\n `route \\`${routeId}\\` threw the following error:\\n${message}`;\n } else if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return { result, idx: i };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isPromise(val: unknown): val is Promise {\n return typeof val === \"object\" && val != null && \"then\" in val;\n}\n\nfunction isHandlerResult(result: unknown): result is HandlerResult {\n return (\n result != null &&\n typeof result === \"object\" &&\n \"type\" in result &&\n \"result\" in result &&\n (result.type === ResultType.data || result.type === ResultType.error)\n );\n}\n\nfunction isRedirectHandlerResult(result: HandlerResult) {\n return (\n isResponse(result.result) && redirectStatusCodes.has(result.result.status)\n );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\n isFetcher: boolean,\n currentLoaderData?: RouteData\n) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, signal, isFetcher).then((result) => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n if (transitions.size > 0) {\n let json: Record = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n//#endregion\n","import * as React from \"react\";\nimport type {\n AgnosticIndexRouteObject,\n AgnosticNonIndexRouteObject,\n AgnosticRouteMatch,\n History,\n LazyRouteFunction,\n Location,\n Action as NavigationType,\n RelativeRoutingType,\n Router,\n StaticHandlerContext,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticIndexRouteObject[\"path\"];\n id?: AgnosticIndexRouteObject[\"id\"];\n loader?: AgnosticIndexRouteObject[\"loader\"];\n action?: AgnosticIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticIndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction;\n}\n\nexport interface NonIndexRouteObject {\n caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticNonIndexRouteObject[\"path\"];\n id?: AgnosticNonIndexRouteObject[\"id\"];\n loader?: AgnosticNonIndexRouteObject[\"loader\"];\n action?: AgnosticNonIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticNonIndexRouteObject[\"handle\"];\n index?: false;\n children?: RouteObject[];\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n children?: DataRouteObject[];\n id: string;\n};\n\nexport interface RouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch {}\n\nexport interface DataRouteMatch extends RouteMatch {}\n\nexport interface DataRouterContextObject\n // Omit `future` since those can be pulled from the `router`\n // `NavigationContext` needs future since it doesn't have a `router` in all cases\n extends Omit {\n router: Router;\n staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n React.createContext(null);\nif (__DEV__) {\n DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext(null);\nif (__DEV__) {\n AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n unstable_viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n createHref: History[\"createHref\"];\n // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n encodeLocation?: History[\"encodeLocation\"];\n go: History[\"go\"];\n push(to: To, state?: any, opts?: NavigateOptions): void;\n replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n basename: string;\n navigator: Navigator;\n static: boolean;\n future: {\n v7_relativeSplatPath: boolean;\n };\n}\n\nexport const NavigationContext = React.createContext(\n null!\n);\n\nif (__DEV__) {\n NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n location: Location;\n navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext(\n null!\n);\n\nif (__DEV__) {\n LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n outlet: React.ReactElement | null;\n matches: RouteMatch[];\n isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext({\n outlet: null,\n matches: [],\n isDataRoute: false,\n});\n\nif (__DEV__) {\n RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext(null);\n\nif (__DEV__) {\n RouteErrorContext.displayName = \"RouteError\";\n}\n","import * as React from \"react\";\nimport type {\n Blocker,\n BlockerFunction,\n Location,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathPattern,\n RelativeRoutingType,\n Router as RemixRouter,\n RevalidationState,\n To,\n UIMatch,\n} from \"@remix-run/router\";\nimport {\n IDLE_BLOCKER,\n Action as NavigationType,\n UNSAFE_convertRouteMatchToUiMatch as convertRouteMatchToUiMatch,\n UNSAFE_getResolveToMatches as getResolveToMatches,\n UNSAFE_invariant as invariant,\n isRouteErrorResponse,\n joinPaths,\n matchPath,\n matchRoutes,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n DataRouteMatch,\n NavigateOptions,\n RouteContextObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n RouteErrorContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/hooks/use-href\n */\nexport function useHref(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useHref() may be used only in the context of a component.`\n );\n\n let { basename, navigator } = React.useContext(NavigationContext);\n let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n let joinedPathname = pathname;\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the href. If this is a root navigation, then just use the raw\n // basename which allows the basename to have full control over the presence\n // of a trailing slash on root links\n if (basename !== \"/\") {\n joinedPathname =\n pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n }\n\n return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a ``.\n *\n * @see https://reactrouter.com/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/hooks/use-location\n */\nexport function useLocation(): Location {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useLocation() may be used only in the context of a component.`\n );\n\n return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * ``.\n *\n * @see https://reactrouter.com/hooks/use-match\n */\nexport function useMatch<\n ParamKey extends ParamParseKey,\n Path extends string\n>(pattern: PathPattern | Path): PathMatch | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useMatch() may be used only in the context of a component.`\n );\n\n let { pathname } = useLocation();\n return React.useMemo(\n () => matchPath(pattern, pathname),\n [pathname, pattern]\n );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n (to: To, options?: NavigateOptions): void;\n (delta: number): void;\n}\n\nconst navigateEffectWarning =\n `You should call navigate() in a React.useEffect(), not when ` +\n `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n cb: Parameters[0]\n) {\n let isStatic = React.useContext(NavigationContext).static;\n if (!isStatic) {\n // We should be able to get rid of this once react 18.3 is released\n // See: https://github.com/facebook/react/pull/26395\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(cb);\n }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by ``s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n let { isDataRoute } = React.useContext(RouteContext);\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useNavigate() may be used only in the context of a component.`\n );\n\n let dataRouterContext = React.useContext(DataRouterContext);\n let { basename, future, navigator } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n\n let routePathnamesJson = JSON.stringify(\n getResolveToMatches(matches, future.v7_relativeSplatPath)\n );\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our history listener yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n navigator.go(to);\n return;\n }\n\n let path = resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n options.relative === \"path\"\n );\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to handing off to history (but only if we're not in a data router,\n // otherwise it'll prepend the basename inside of the router).\n // If this is a root navigation, then we navigate to the raw basename\n // which allows the basename to have full control over the presence of a\n // trailing slash on root links\n if (dataRouterContext == null && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\"\n ? basename\n : joinPaths([basename, path.pathname]);\n }\n\n (!!options.replace ? navigator.replace : navigator.push)(\n path,\n options.state,\n options\n );\n },\n [\n basename,\n navigator,\n routePathnamesJson,\n locationPathname,\n dataRouterContext,\n ]\n );\n\n return navigate;\n}\n\nconst OutletContext = React.createContext(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/hooks/use-outlet-context\n */\nexport function useOutletContext(): Context {\n return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `` to render child routes.\n *\n * @see https://reactrouter.com/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n let outlet = React.useContext(RouteContext).outlet;\n if (outlet) {\n return (\n {outlet}\n );\n }\n return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/hooks/use-params\n */\nexport function useParams<\n ParamsOrKey extends string | Record = string\n>(): Readonly<\n [ParamsOrKey] extends [string] ? Params : Partial\n> {\n let { matches } = React.useContext(RouteContext);\n let routeMatch = matches[matches.length - 1];\n return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n let { future } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n let routePathnamesJson = JSON.stringify(\n getResolveToMatches(matches, future.v7_relativeSplatPath)\n );\n\n return React.useMemo(\n () =>\n resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n relative === \"path\"\n ),\n [to, routePathnamesJson, locationPathname, relative]\n );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/hooks/use-routes\n */\nexport function useRoutes(\n routes: RouteObject[],\n locationArg?: Partial | string\n): React.ReactElement | null {\n return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n routes: RouteObject[],\n locationArg?: Partial | string,\n dataRouterState?: RemixRouter[\"state\"],\n future?: RemixRouter[\"future\"]\n): React.ReactElement | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useRoutes() may be used only in the context of a component.`\n );\n\n let { navigator } = React.useContext(NavigationContext);\n let { matches: parentMatches } = React.useContext(RouteContext);\n let routeMatch = parentMatches[parentMatches.length - 1];\n let parentParams = routeMatch ? routeMatch.params : {};\n let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n let parentRoute = routeMatch && routeMatch.route;\n\n if (__DEV__) {\n // You won't get a warning about 2 different under a \n // without a trailing *, but this is a best-effort warning anyway since we\n // cannot even give the warning unless they land at the parent route.\n //\n // Example:\n //\n // \n // {/* This route path MUST end with /* because otherwise\n // it will never match /blog/post/123 */}\n // } />\n // } />\n // \n //\n // function Blog() {\n // return (\n // \n // } />\n // \n // );\n // }\n let parentPath = (parentRoute && parentRoute.path) || \"\";\n warningOnce(\n parentPathname,\n !parentRoute || parentPath.endsWith(\"*\"),\n `You rendered descendant (or called \\`useRoutes()\\`) at ` +\n `\"${parentPathname}\" (under ) but the ` +\n `parent route path has no trailing \"*\". This means if you navigate ` +\n `deeper, the parent won't match anymore and therefore the child ` +\n `routes will never render.\\n\\n` +\n `Please change the parent to .`\n );\n }\n\n let locationFromContext = useLocation();\n\n let location;\n if (locationArg) {\n let parsedLocationArg =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n invariant(\n parentPathnameBase === \"/\" ||\n parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n `When overriding the location using \\`\\` or \\`useRoutes(routes, location)\\`, ` +\n `the location pathname must begin with the portion of the URL pathname that was ` +\n `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n );\n\n location = parsedLocationArg;\n } else {\n location = locationFromContext;\n }\n\n let pathname = location.pathname || \"/\";\n\n let remainingPathname = pathname;\n if (parentPathnameBase !== \"/\") {\n // Determine the remaining pathname by removing the # of URL segments the\n // parentPathnameBase has, instead of removing based on character count.\n // This is because we can't guarantee that incoming/outgoing encodings/\n // decodings will match exactly.\n // We decode paths before matching on a per-segment basis with\n // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n // match what `window.location.pathname` would reflect. Those don't 100%\n // align when it comes to encoded URI characters such as % and &.\n //\n // So we may end up with:\n // pathname: \"/descendant/a%25b/match\"\n // parentPathnameBase: \"/descendant/a%b\"\n //\n // And the direct substring removal approach won't work :/\n let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n }\n\n let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n if (__DEV__) {\n warning(\n parentRoute || matches != null,\n `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n );\n\n warning(\n matches == null ||\n matches[matches.length - 1].route.element !== undefined ||\n matches[matches.length - 1].route.Component !== undefined ||\n matches[matches.length - 1].route.lazy !== undefined,\n `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n `does not have an element or Component. This means it will render an with a ` +\n `null value by default resulting in an \"empty\" page.`\n );\n }\n\n let renderedMatches = _renderMatches(\n matches &&\n matches.map((match) =>\n Object.assign({}, match, {\n params: Object.assign({}, parentParams, match.params),\n pathname: joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathname).pathname\n : match.pathname,\n ]),\n pathnameBase:\n match.pathnameBase === \"/\"\n ? parentPathnameBase\n : joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathnameBase).pathname\n : match.pathnameBase,\n ]),\n })\n ),\n parentMatches,\n dataRouterState,\n future\n );\n\n // When a user passes in a `locationArg`, the associated routes need to\n // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n // to use the scoped location instead of the global location.\n if (locationArg && renderedMatches) {\n return (\n \n {renderedMatches}\n \n );\n }\n\n return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n let error = useRouteError();\n let message = isRouteErrorResponse(error)\n ? `${error.status} ${error.statusText}`\n : error instanceof Error\n ? error.message\n : JSON.stringify(error);\n let stack = error instanceof Error ? error.stack : null;\n let lightgrey = \"rgba(200,200,200, 0.5)\";\n let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n let devInfo = null;\n if (__DEV__) {\n console.error(\n \"Error handled by React Router default ErrorBoundary:\",\n error\n );\n\n devInfo = (\n <>\n

💿 Hey developer 👋

\n

\n You can provide a way better UX than this when your app throws errors\n by providing your own ErrorBoundary or{\" \"}\n errorElement prop on your route.\n

\n \n );\n }\n\n return (\n <>\n

Unexpected Application Error!

\n

{message}

\n {stack ?
{stack}
: null}\n {devInfo}\n \n );\n}\n\nconst defaultErrorElement = ;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n location: Location;\n revalidation: RevalidationState;\n error: any;\n component: React.ReactNode;\n routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n location: Location;\n revalidation: RevalidationState;\n error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n RenderErrorBoundaryProps,\n RenderErrorBoundaryState\n> {\n constructor(props: RenderErrorBoundaryProps) {\n super(props);\n this.state = {\n location: props.location,\n revalidation: props.revalidation,\n error: props.error,\n };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error: error };\n }\n\n static getDerivedStateFromProps(\n props: RenderErrorBoundaryProps,\n state: RenderErrorBoundaryState\n ) {\n // When we get into an error state, the user will likely click \"back\" to the\n // previous page that didn't have an error. Because this wraps the entire\n // application, that will have no effect--the error page continues to display.\n // This gives us a mechanism to recover from the error when the location changes.\n //\n // Whether we're in an error state or not, we update the location in state\n // so that when we are in an error state, it gets reset when a new location\n // comes in and the user recovers from the error.\n if (\n state.location !== props.location ||\n (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n ) {\n return {\n error: props.error,\n location: props.location,\n revalidation: props.revalidation,\n };\n }\n\n // If we're not changing locations, preserve the location but still surface\n // any new errors that may come through. We retain the existing error, we do\n // this because the error provided from the app state may be cleared without\n // the location changing.\n return {\n error: props.error !== undefined ? props.error : state.error,\n location: state.location,\n revalidation: props.revalidation || state.revalidation,\n };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"React Router caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n return this.state.error !== undefined ? (\n \n \n \n ) : (\n this.props.children\n );\n }\n}\n\ninterface RenderedRouteProps {\n routeContext: RouteContextObject;\n match: RouteMatch;\n children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n let dataRouterContext = React.useContext(DataRouterContext);\n\n // Track how deep we got in our render pass to emulate SSR componentDidCatch\n // in a DataStaticRouter\n if (\n dataRouterContext &&\n dataRouterContext.static &&\n dataRouterContext.staticContext &&\n (match.route.errorElement || match.route.ErrorBoundary)\n ) {\n dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n }\n\n return (\n \n {children}\n \n );\n}\n\nexport function _renderMatches(\n matches: RouteMatch[] | null,\n parentMatches: RouteMatch[] = [],\n dataRouterState: RemixRouter[\"state\"] | null = null,\n future: RemixRouter[\"future\"] | null = null\n): React.ReactElement | null {\n if (matches == null) {\n if (dataRouterState?.errors) {\n // Don't bail if we have data router errors so we can render them in the\n // boundary. Use the pre-matched (or shimmed) matches\n matches = dataRouterState.matches as DataRouteMatch[];\n } else {\n return null;\n }\n }\n\n let renderedMatches = matches;\n\n // If we have data errors, trim matches to the highest error boundary\n let errors = dataRouterState?.errors;\n if (errors != null) {\n let errorIndex = renderedMatches.findIndex(\n (m) => m.route.id && errors?.[m.route.id] !== undefined\n );\n invariant(\n errorIndex >= 0,\n `Could not find a matching route for errors on route IDs: ${Object.keys(\n errors\n ).join(\",\")}`\n );\n renderedMatches = renderedMatches.slice(\n 0,\n Math.min(renderedMatches.length, errorIndex + 1)\n );\n }\n\n // If we're in a partial hydration mode, detect if we need to render down to\n // a given HydrateFallback while we load the rest of the hydration data\n let renderFallback = false;\n let fallbackIndex = -1;\n if (dataRouterState && future && future.v7_partialHydration) {\n for (let i = 0; i < renderedMatches.length; i++) {\n let match = renderedMatches[i];\n // Track the deepest fallback up until the first route without data\n if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n fallbackIndex = i;\n }\n\n if (match.route.id) {\n let { loaderData, errors } = dataRouterState;\n let needsToRunLoader =\n match.route.loader &&\n loaderData[match.route.id] === undefined &&\n (!errors || errors[match.route.id] === undefined);\n if (match.route.lazy || needsToRunLoader) {\n // We found the first route that's not ready to render (waiting on\n // lazy, or has a loader that hasn't run yet). Flag that we need to\n // render a fallback and render up until the appropriate fallback\n renderFallback = true;\n if (fallbackIndex >= 0) {\n renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n } else {\n renderedMatches = [renderedMatches[0]];\n }\n break;\n }\n }\n }\n }\n\n return renderedMatches.reduceRight((outlet, match, index) => {\n // Only data routers handle errors/fallbacks\n let error: any;\n let shouldRenderHydrateFallback = false;\n let errorElement: React.ReactNode | null = null;\n let hydrateFallbackElement: React.ReactNode | null = null;\n if (dataRouterState) {\n error = errors && match.route.id ? errors[match.route.id] : undefined;\n errorElement = match.route.errorElement || defaultErrorElement;\n\n if (renderFallback) {\n if (fallbackIndex < 0 && index === 0) {\n warningOnce(\n \"route-fallback\",\n false,\n \"No `HydrateFallback` element provided to render during initial hydration\"\n );\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = null;\n } else if (fallbackIndex === index) {\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n }\n }\n }\n\n let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n let getChildren = () => {\n let children: React.ReactNode;\n if (error) {\n children = errorElement;\n } else if (shouldRenderHydrateFallback) {\n children = hydrateFallbackElement;\n } else if (match.route.Component) {\n // Note: This is a de-optimized path since React won't re-use the\n // ReactElement since it's identity changes with each new\n // React.createElement call. We keep this so folks can use\n // `` in `` but generally `Component`\n // usage is only advised in `RouterProvider` when we can convert it to\n // `element` ahead of time.\n children = ;\n } else if (match.route.element) {\n children = match.route.element;\n } else {\n children = outlet;\n }\n return (\n \n );\n };\n // Only wrap in an error boundary within data router usages when we have an\n // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to\n // an ancestor ErrorBoundary/errorElement\n return dataRouterState &&\n (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n \n ) : (\n getChildren()\n );\n }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n UseBlocker = \"useBlocker\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n UseBlocker = \"useBlocker\",\n UseLoaderData = \"useLoaderData\",\n UseActionData = \"useActionData\",\n UseRouteError = \"useRouteError\",\n UseNavigation = \"useNavigation\",\n UseRouteLoaderData = \"useRouteLoaderData\",\n UseMatches = \"useMatches\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n let route = React.useContext(RouteContext);\n invariant(route, getDataRouterConsoleError(hookName));\n return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n let route = useRouteContext(hookName);\n let thisRoute = route.matches[route.matches.length - 1];\n invariant(\n thisRoute.route.id,\n `${hookName} can only be used on routes that contain a unique \"id\"`\n );\n return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n return React.useMemo(\n () => ({\n revalidate: dataRouterContext.router.revalidate,\n state: state.revalidation,\n }),\n [dataRouterContext.router.revalidate, state.revalidation]\n );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches(): UIMatch[] {\n let { matches, loaderData } = useDataRouterState(\n DataRouterStateHook.UseMatches\n );\n return React.useMemo(\n () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n [matches, loaderData]\n );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n if (state.errors && state.errors[routeId] != null) {\n console.error(\n `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n );\n return undefined;\n }\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseActionData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error. This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n let error = React.useContext(RouteErrorContext);\n let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n // If this was a render error, we put it in a RouteError context inside\n // of RenderErrorBoundary\n if (error !== undefined) {\n return error;\n }\n\n // Otherwise look for errors from our data router state\n return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `` value\n */\nexport function useAsyncValue(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `` value\n */\nexport function useAsyncError(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation. Mostly used to avoid\n * using half-filled form data. This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n let [blockerKey, setBlockerKey] = React.useState(\"\");\n let blockerFunction = React.useCallback(\n (arg) => {\n if (typeof shouldBlock !== \"function\") {\n return !!shouldBlock;\n }\n if (basename === \"/\") {\n return shouldBlock(arg);\n }\n\n // If they provided us a function and we've got an active basename, strip\n // it from the locations we expose to the user to match the behavior of\n // useLocation\n let { currentLocation, nextLocation, historyAction } = arg;\n return shouldBlock({\n currentLocation: {\n ...currentLocation,\n pathname:\n stripBasename(currentLocation.pathname, basename) ||\n currentLocation.pathname,\n },\n nextLocation: {\n ...nextLocation,\n pathname:\n stripBasename(nextLocation.pathname, basename) ||\n nextLocation.pathname,\n },\n historyAction,\n });\n },\n [basename, shouldBlock]\n );\n\n // This effect is in charge of blocker key assignment and deletion (which is\n // tightly coupled to the key)\n React.useEffect(() => {\n let key = String(++blockerId);\n setBlockerKey(key);\n return () => router.deleteBlocker(key);\n }, [router]);\n\n // This effect handles assigning the blockerFunction. This is to handle\n // unstable blocker function identities, and happens only after the prior\n // effect so we don't get an orphaned blockerFunction in the router with a\n // key of \"\". Until then we just have the IDLE_BLOCKER.\n React.useEffect(() => {\n if (blockerKey !== \"\") {\n router.getBlocker(blockerKey, blockerFunction);\n }\n }, [router, blockerKey, blockerFunction]);\n\n // Prefer the blocker from `state` not `router.state` since DataRouterContext\n // is memoized so this ensures we update on blocker state updates\n return blockerKey && state.blockers.has(blockerKey)\n ? state.blockers.get(blockerKey)!\n : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our router subscriber yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n router.navigate(to);\n } else {\n router.navigate(to, { fromRouteId: id, ...options });\n }\n },\n [router, id]\n );\n\n return navigate;\n}\n\nconst alreadyWarned: Record = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n if (!cond && !alreadyWarned[key]) {\n alreadyWarned[key] = true;\n warning(false, message);\n }\n}\n","import type {\n InitialEntry,\n LazyRouteFunction,\n Location,\n MemoryHistory,\n RelativeRoutingType,\n Router as RemixRouter,\n RouterState,\n RouterSubscriber,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\nimport {\n AbortedDeferredError,\n Action as NavigationType,\n createMemoryHistory,\n UNSAFE_getResolveToMatches as getResolveToMatches,\n UNSAFE_invariant as invariant,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\nimport * as React from \"react\";\n\nimport type {\n DataRouteObject,\n IndexRouteObject,\n Navigator,\n NonIndexRouteObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n} from \"./context\";\nimport {\n _renderMatches,\n useAsyncValue,\n useInRouterContext,\n useLocation,\n useNavigate,\n useOutlet,\n useRoutes,\n useRoutesImpl,\n} from \"./hooks\";\n\nexport interface FutureConfig {\n v7_relativeSplatPath: boolean;\n v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n fallbackElement?: React.ReactNode;\n router: RemixRouter;\n // Only accept future flags relevant to rendering behavior\n // routing flags should be accessed via router.future\n future?: Partial>;\n}\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n fallbackElement,\n router,\n future,\n}: RouterProviderProps): React.ReactElement {\n let [state, setStateImpl] = React.useState(router.state);\n let { v7_startTransition } = future || {};\n\n let setState = React.useCallback(\n (newState: RouterState) => {\n if (v7_startTransition && startTransitionImpl) {\n startTransitionImpl(() => setStateImpl(newState));\n } else {\n setStateImpl(newState);\n }\n },\n [setStateImpl, v7_startTransition]\n );\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n React.useEffect(() => {\n warning(\n fallbackElement == null || !router.future.v7_partialHydration,\n \"`` is deprecated when using \" +\n \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n );\n // Only log this once on initial mount\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n let navigator = React.useMemo((): Navigator => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: (n) => router.navigate(n),\n push: (to, state, opts) =>\n router.navigate(to, {\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n replace: (to, state, opts) =>\n router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n };\n }, [router]);\n\n let basename = router.basename || \"/\";\n\n let dataRouterContext = React.useMemo(\n () => ({\n router,\n navigator,\n static: false,\n basename,\n }),\n [router, navigator, basename]\n );\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a